我正在vtk/QT环境中用c++编写一个程序。然而,这个问题主要是一个方法/算法的问题。
我试图同步我的三个正在运行的线程: 1.线程:一次传输一个样本,并将其添加到“输出”缓冲区2.线程:一次接收一个样本,并将其添加到“输入”缓冲区3.线程:从“输出”和“输入”缓冲区中提取数据,并将它们添加到单独的绘图缓冲区,以便渲染。
我希望这些线程同步运行,并尝试了一种方法,即我将一个条件变量与每个线程的布尔条件一起使用,其中一个线程向下一个线程发出信号,因此在循环中是第四个,按照上面列出的顺序。然而,当我这样做时,我得到了一个死锁,我的程序停止了。我真的很感谢这里的一些意见:)
以下是我在代码中的方法:
//布尔变量的Initialcondition:
readyForTransmit=true;
readyForReceive=false;
readyForPlotting=false;线程1-传输:
while(1){
mutex->Lock();
//waits for condition/signal to proceed
while(!readyForTransmit)
transmitConditionVariable->wait(mutex);
readyForTransmit=false;
mutex->Unlock();
//Here I transmit my sample
transmit();
//Triggers next thread - reception
mutex->Lock();
readyForReceive=true;
receiveConditionVariable->broadcast(); //Have also tried signal();
mutex->Unlock();
}线程2-接收:
while(1){
mutex->Lock();
//waits for condition/signal to proceed
while(!readyForReceive)
receiveConditionVariable->wait(mutex);
readyForReceive=false;
mutex->Unlock();
//Here I receive my sample
receive();
//Triggers next thread - reception
mutex->Lock();
readyForPlotting=true;
plottingConditionVariable->broadcast(); //Have also tried signal();
mutex->Unlock();
}线程3-添加到绘图缓冲区:
while(1){
mutex->Lock();
//waits for condition/signal to proceed
while(!readyForPlotting)
plottingConditionVariable->wait(mutex);
readyForPlotting=false;
mutex->Unlock();
//Here I adds samples to plotting buffer
updatePlottingBuffers();
//Triggers next thread - reception
mutex->Lock();
readyForTransmit=true;
transmitConditionVariable->broadcast(); //Have also tried signal();
mutex->Unlock();
}除此之外,我将线程安全的样本推送到缓冲区和从缓冲区拉出。所以这应该不是问题。
期待您的回音!=)
发布于 2013-07-18 18:57:47
https://stackoverflow.com/questions/17719767
复制相似问题