admin管理员组文章数量:1292656
I have a queue of worker thread IDs in C++, and a coordinator thread wakes each thread in order. The woken thread then interacts with the coordinator thread to perform some work. Once done, the coordinator wakes the next thread.
I am considering two approaches to implement this:
- Separate Condition Variables: Each worker thread has its own
std::condition_variable
, stored in a queue along with its thread ID. The coordinator signals the respective condition variable to wake up a specific thread. - Single Condition Variable: All worker threads wait on a shared
std::condition_variable
, using a predicate to check if their ID matches the one chosen by the coordinator.
Approach 2: Using a Single Condition Variable
Coordinator Thread:
while (true) {
{
std::lock_guard<std::mutex> lock(mtx);
id_chosen_by_coordinator = workerThreads.front();
workerThreads.pop();
}
cv.notify_all(); // Wake up all worker threads, but only one will proceed
...
}
Worker Thread:
std::unique_lock<std::mutex> lock(mtx);
cv.wait(lock, []() { return myid == id_chosen_by_coordinator; });
...
Which of these approaches is preferable in terms of efficiency and correctness? Are there potential pitfalls with the single condition variable approach, such as unnecessary wake-ups or race conditions?
版权声明:本文标题:multithreading - Managing Worker Thread Wake-Up in C++: Separate vs. Shared Condition Variables? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741558286a2385292.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论