I try to write the following code. and I get this problem.
Basically, I understand my problem is the same as this question: std::condition_variable not properly wakes up after std::condition_variable::notify_all() from other thread.
constexpr size_t times = 10;
vector<thread> threadpool;
shared_ptr<condition_variable> cv = make_shared<condition_variable>();
shared_ptr<mutex> m = make_shared<mutex>();
for (size_t i = 0; i < times; ++i)
{
threadpool.push_back(thread([m, cv]()
{
std::unique_lock<std::mutex> lk(*m);
cv->wait(lk);
//do some thing
//cout << std::this_thread::get_id << endl;
}));
}
for (auto& t : threadpool)
{
t.detach();
}
//std::this_thread::sleep_for(std::chrono::seconds(2));//sleep enough time
cv->notify_all();
//do some thing
After sleeping for awhile, I send a notify to all threads, they are received. But my question is, can I do this without sleeping?