我有以下計時代碼,它似乎沒有等待條件變量根據需要。目標是產生所有線程,然後讓他們同時開始工作。正確使用條件變量
過早似乎被稱爲。任何想法爲什麼?
chrono::milliseconds timeNThreadsLockFree(int n, int worksize)
{
boost::lockfree::stack<int> data(totalNumberOfWorkItems);
vector<thread> ts;
atomic<int> count;
condition_variable cv;
mutex mut2;
unique_lock<mutex> ul(mut2,defer_lock);
lock(ul,mut);
auto startSpawn = chrono::high_resolution_clock::now();
for (int i = 0; i < n; i++)
ts.push_back(thread([&](){
cv.wait(ul, [](){return true; });
int q = 5;
for (int j = 0; j < worksize; j++){
data.push(7);
else count++;}
}));
if (count != 0) {
cout << "premature" << endl; }
cv.notify_all();
auto startWait = chrono::high_resolution_clock::now();
for (auto&& t : ts)
t.join();
auto endWait = chrono::high_resolution_clock::now();
if (count != totalNumberOfWorkItems)
cout << "not done" << endl;
return chrono::duration_cast<chrono::milliseconds>(endWait - startWait);
}
如果我刪除拉姆達我得到「鎖定正在舉行由不同的上下文」的斷言在Visual Studio中失敗。如果我使lambda返回false,那也是一樣。想法? – soandos
另一件需要注意的事情是,我從來不希望鎖需要重新獲取。在這種情況下是否做到了? – soandos
@soandos如果你嘗試在每個線程內部用相同的互斥體創建一個單獨的'std :: unique_lock',然後嘗試等待呢? – Xymostech