【发布时间】:2016-02-27 13:50:01
【问题描述】:
似乎condition_variable notify_one 并不总是按应有的方式工作。
struct Task {
std::mutex mutex;
std::condition_variable cv;
std::atomic_bool launch{false};
};
void job(Task& task) {
std::unique_lock<std::mutex> lock{task.mutex};
task.cv.wait(lock, [&]{ return task.launch == true; });
}
int main() {
for (auto i=0 ; i<1000*1000 ; i++) {
Task task;
std::thread thread{job, std::ref(task)};
task.launch = true;
task.cv.notify_one();
thread.join();
}
}
这个程序几乎永远不会到达终点,它在绝大多数情况下都永远停止在循环中。 为什么会这样?
【问题讨论】:
-
会发生什么,您预计会发生什么?这些是一个好问题的基本部分......
-
谢谢@UlrichEckhardt,我希望程序能够完成,但它几乎永远不会完成。
-
它到底挂在哪里?哪一行是最后成功执行的?
标签: c++ multithreading concurrency parallel-processing