0

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?

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
viho
  • 1
  • 1
  • 2
  • 2
    You are using condition variables incorrectly. A condition variable is supposed to represent a condition; hence the name. One thread would lock the mutex, then check the condition, and only if it's not currently true would it wait on the condition variable. The other thread would make the condition true, then notify the condition variable. You are trying to invent `std::latch` or `std::barrier` – Igor Tandetnik May 01 '21 at 04:32
  • I'm not even sure what you're trying to achieve. Please, as a new user here, take the [tour] and read [ask]. – Ulrich Eckhardt May 01 '21 at 06:54
  • You cannot possibly know what happens first, `wait` or `notify`. If `notify` happens first, the signal is lost and now your threads are waiting for a notification that will never come. If you need to insert `sleep` to make it work, it is still broken. – n. m. could be an AI May 01 '21 at 07:35

0 Answers0