mardi 11 juillet 2023

What if cv.notify_one() is called before cv.wait?

Question solved(realized my mistake).
- I'll leave this question undeleted for future learners, but let me know if it's inappropriate.


This is an example code for std::condition_variable in cppreference.com:

#include <iostream>
#include <string>
#include <thread>
#include <mutex>
#include <condition_variable>
 
std::mutex m;
std::condition_variable cv;
std::string data;
bool ready = false;
bool processed = false;
 
void worker_thread()
{
    // Wait until main() sends data
    std::unique_lock lk(m);
    cv.wait(lk, []{return ready;});
 
    // after the wait, we own the lock.
    std::cout << "Worker thread is processing data\n";
    data += " after processing";
 
    // Send data back to main()
    processed = true;
    std::cout << "Worker thread signals data processing completed\n";
 
    // Manual unlocking is done before notifying, to avoid waking up
    // the waiting thread only to block again (see notify_one for details)
    lk.unlock();
    cv.notify_one();
}
 
int main()
{
    std::thread worker(worker_thread);
 
    data = "Example data";
    // send data to the worker thread
    {
        std::lock_guard lk(m);
        ready = true;
        std::cout << "main() signals data ready for processing\n";
    } 
    cv.notify_one(); // <-What if the main thread executes until here, before the worker thread wait?
 
    // wait for the worker
    {
        std::unique_lock lk(m); // <-Edit: what if main thread lock first?
        cv.wait(lk, []{return processed;});
    }
    std::cout << "Back in main(), data = " << data << '\n';
 
    worker.join();
}

As I commented in the above code, let's say the main thread executes the cv.notify_one() before the worker thread does cv.wait(lk, []{return ready;}). Isn't this a deadlock?

std::condition_variable::notify_one page of cppreference.com also seems to mention this situation:

This makes it impossible for notify_one() to, for example, be delayed and unblock a thread that started waiting just after the call to notify_one() was made.

How does the above code not have any problem(deadlock)?

Edit: I think the wait overload is equivalent to while (!ready) {wait(lk);} so it would be ok, but still, what if the main thread acquires the std::unique_lock lk(m); first?

Edit2: (Question resolved) Sorry, my mistake. since the wait overload is equivalent to while (!ready) {wait(lk);} so it would be ok, and even if the main thread acquires the std::unique_lock lk(m); first, no problem because lk would be unlocked when the main thread executes cv.wait(lk, []{return processed;});.

Aucun commentaire:

Enregistrer un commentaire