升压同步 [英] Boost synchronization
问题描述
我有NUM_THREADS个线程,我的线程中有以下代码:
I have NUM_THREADS threads, with the following codes in my thread:
/*
Calculate some_value;
*/
//Critical section to accummulate all thresholds
{
boost::mutex::scoped_lock lock(write_mutex);
T += some_value;
num_threads++;
if (num_threads == NUM_THREADS){
T = T/NUM_THREADS;
READY = true;
cond.notify_all();
num_threads = 0;
}
}
//Wait for average threshold to be ready
if (!READY)
{
boost::unique_lock<boost::mutex> lock(wait_mutex);
while (!READY){
cond.wait(lock);
}
}
//End critical section
/*
do_something;
*/
基本上,我想让所有线程等待READY信号, 。在创建线程之前,num_thread设置为0,READY为false。偶尔发生死锁。任何人可以帮助吗?
所有的boost变量全局声明如下:
Basically, I want all the threads to wait for the READY signal before continuing. num_thread is set to 0, and READY is false before threads are created. Once in a while, deadlock occurs. Can anyone help please? All the boost variables are globally declared as follows:
boost::mutex write_mutex;
boost::mutex wait_mutex;
boost::condition cond;
推荐答案
代码在 READY
标志(我假设它只是一个 bool
变量)。可能发生什么(即线程执行交错的一个可能的变体)是:
The code has a race condition on the READY
flag (which I assume is just a bool
variable). What may happen (i.e. one possible variant of thread execution interleaving) is:
Thread T1: Thread T2:
if (!READY)
{
unique_lock<mutex> lock(wait_mutex); mutex::scoped_lock lock(write_mutex);
while (!READY) /* ... */
{ READY = true;
/* !!! */ cond.notify_all();
cond.wait(lock);
}
}
测试 READY
标志不与代码设置同步(注意这些关键部分的锁是不同的)。当T1处于标志测试和等待 cond
之间的空洞时,T2可以设置标志并发送信号到 cond
The code testing the READY
flag is not synchronized with the code setting it (note the locks are different for these critical sections). And when T1 is in a "hole" between the flag test and waiting at cond
, T2 may set the flag and send a signal to cond
which T1 may miss.
最简单的解决方法是锁定正确的mutex以更新 READY
and condition notification:
The simplest solution is to lock the right mutex for the update of READY
and condition notification:
/*...*/
T = T/NUM_THREADS;
{
boost::mutex::scoped_lock lock(wait_mutex);
READY = true;
cond.notify_all();
}
这篇关于升压同步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!