我試圖用 C boost::threadpool和. 似乎程式將停止在,但我不知道為什么會發生這種情況。condition_variablemutexboost::threadpool::pool::wait()
#include <boost/threadpool.hpp>
#include <condition_variable>
#include <iostream>
#include <mutex>
using namespace std;
enum {
Running,
Stopped,
Exiting
};
class C {
private:
int m_iStatus;
mutex m_mtx;
condition_variable m_cond;
boost::threadpool::pool m_tp;
public:
C() : m_iStatus(Stopped), m_tp(8) {}
void Start();
void Exit();
private:
bool Check();
void Dispatcher();
};
bool C::Check()
{
unique_lock<mutex> lk(m_mtx);
if (m_iStatus == Stopped)
m_cond.wait(lk);
if (m_iStatus == Exiting)
return false;
else
return true;
}
void C::Dispatcher()
{
if (!Check())
return;
unique_lock<mutex> lk(m_mtx);
// do something...
cout << "." << endl;
m_tp.schedule(bind(&C::Dispatcher, this));
}
void C::Start()
{
unique_lock<mutex> lk(m_mtx);
m_iStatus = Running;
m_tp.schedule(bind(&C::Dispatcher, this));
}
void C::Exit()
{
unique_lock<mutex> lk(m_mtx);
m_iStatus = Exiting;
m_cond.notify_all(); /* notify those waiting on m_cond */
m_tp.wait(); /* went wrong here */
}
int main()
{
C c;
c.Start();
/* wait for a moment */
Sleep(1000);
/* then call Exit */
c.Exit();
return 0;
}
uj5u.com熱心網友回復:
您在仍持有互斥鎖的同時進入等待呼叫。這將阻止其他執行緒完成他們的作業。
在您的特定情況下,m_cond條件變數正在同一個互斥鎖上等待,因此m_cond.wait(lk);只要互斥鎖仍由另一個執行緒持有,對的呼叫將無法回傳。
對此的一種解決方案是在通知條件變數和等待執行緒池完成之間放棄對互斥鎖的鎖定:
{
unique_lock<mutex> lk(m_mtx);
m_iStatus = Exiting;
m_cond.notify_all(); /* notify those waiting on m_cond */
} // lock on m_mtx gets released here
m_tp.wait(); /* this should run fine now */
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/433430.html
下一篇:如何運行多個倒計時
