在多线程应用程序中是否可以在不使用全局计数器的情况下打印奇数和偶数

Is it possible to print odd and even numbers without using global counter in multi-threaded application

有了全局计数器,我们可以在多线程应用程序中使用互斥量(用于拥有资源)和条件变量(用于向其他线程发送信号)来逐个打印奇数和偶数。

但是我们如何在不使用全局计数器的情况下实现同样的目标呢?

But How do we achieve same without using global counter?

为什么需要全局计数器?等待并向另一个线程发出信号的方法是 all 你需要的。

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
  }
}