【发布时间】:2011-02-23 11:59:03
【问题描述】:
我希望有两个线程。第一个thread1偶尔会调用如下伪函数:
void waitForThread2() {
if (thread2 is not idle) {
return;
}
notifyThread2IamReady(); // i.e. via 1st condition variable
Wait for thread2 to finish exclusive access. // i.e. via 2nd condition variable.
}
第二个线程2永远在下面的伪循环中:
for (;;) {
Notify thread1 I am idle.
Wait for thread1 to be ready. // i.e. via 1st condition variable.
Notify thread1 I am exclusive.
Do some work while thread1 is blocked.
Notify thread1 I am busy. // i.e. via 2nd condition variable.
Do some work in parallel with thread1.
}
编写此代码的最佳方法是什么,以使线程 1 和线程 2 在具有多核的机器上尽可能保持忙碌。我想避免一个线程的通知和另一个线程的检测之间的长时间延迟。我尝试使用 pthread 条件变量,但发现线程 2 执行“通知线程 1 我很忙”与 thear2IsExclusive() 上的 waitForThread2() 中的循环之间的延迟可能长达近一秒。然后我尝试使用 volatile sig_atomic_t 共享变量来控制它,但是出了点问题,所以我一定没有正确地做。
【问题讨论】:
-
你最好告诉人们你真正想要解决的问题,而不是要求他们实施你已经构想的解决方案......
-
您的伪代码没有多大意义。你如何通知另一个你很忙的线程,为什么?此外,您在这里关注线程;通常,您需要同步数据。您正在同步哪些数据,您的并行操作如何?
-
如果您的 condvars 需要一秒钟的时间来做任何事情,那么您就做错了。此外,规范的做法是锁定数据结构,而不是“通知另一个线程”;后者无法扩展。
-
@tc 大多数时候 cond var 很快,但有时可能需要接近一秒。
-
@WhirlWind 并行工作是在单独的数据上,因此不需要同步。目前,我通过条件变量通知我正忙的另一个线程。他们之所以通知是因为在短暂的忙碌期间,thread2正在修改thread1查看的数据结构。
标签: c++ pthreads mutex condition-variable