With global counter, we can use mutex(for Owning Resource) and Conditional Variable(For Signaling other thread) in multi-threaded application to print odd and even numbers on-by-one.
But How do we achieve same without using global counter?
But How do we achieve same without using global counter?
Why do you need a global counter? A way to wait for and signal the other thread is all you need.
void odd(void *ignore)
{
for (int j = 1; ; j += 1) {
printf("%d\n", j);
// signal other thread
// wait for it to signal me
}
}
void even(void *ignore)
{
for (int j = 2; ; j += 2) {
// wait for other thread to signal me
printf("%d\n", j);
// signal other thread
}
}