[英]Synchronizing of Threadpool
在每個時間步中,多個工作線程 W[1..10] 應該空閑,直到它們從主線程發出信號開始工作。 完成他們的每一項工作,向主線程發信號通知他們已經完成並返回到他們之前處於的等待狀態。 主線程應該在工作線程完成工作時等待。
我試圖使用std::condition_variable
std::mutex
來做到這一點,但失敗了。 不使用 boost 或其他高級庫解決問題的正確方法是什么? 出於性能原因,我想避免在每個步驟中生成和加入線程。 非常感謝。
編輯:
const size_t thread_num = 10;
int busy_count = thread_num;
std::condition_variable cv;
std::mutex cv_m;
std::condition_variable cv_lock1;
std::mutex cv_m_lock1;
bool lock_1;
bool end_all = false;
void wthread()
{
do {
{
std::unique_lock<std::mutex> lk(cv_m_lock1);
cv_lock1.wait(lk, []{return lock_1 == false; });
}
if (end_all)
{
std::cout << "exit\n";
return;
}
// do work
{
std::lock_guard<std::mutex> lk(cv_m);
busy_count--;
std::cout << busy_count << " ";
}
cv.notify_all();
{
std::unique_lock<std::mutex> lk(cv_m_lock1);
cv_lock1.wait(lk, []{return lock_1 == true; });
}
} while (true);
}
int _tmain(int argc, _TCHAR* argv[])
{
std::thread *t[thread_num];
lock_1 = true;
for (unsigned int i = 0; i < thread_num; i++)
t[i] = new std::thread(wthread);
for (int i = 0; i < 10; i++)
{
busy_count = 10;
lock_1 = false;
cv_lock1.notify_all();
{
std::unique_lock<std::mutex> lk(cv_m);
cv.wait(lk, []{return busy_count == 0; });
}
lock_1 = true;
cv_lock1.notify_all();
}
end_all = true;
lock_1 = false;
cv_lock1.notify_all();
for (unsigned int i = 0; i < thread_num; i++)
t[i]->join();
return 0;
}
就像是
std::thread thread1([](){/*do something*/});
std::thread thread2([](){/*do something*/});
std::thread thread3([](){/*do something*/});
thread1.join();
thread2.join();
thread3.join();
主線程將等到線程 1..3 完成工作; 這些線程將同時工作
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.