Mutex protecting std::condition_variable

对着背影说爱祢 提交于 2020-06-23 00:43:42

问题


Even if the shared variable is atomic, it must be modified under the mutex in order to correctly publish the modification to the waiting thread. Any thread that intends to wait on std::condition_variable has to acquire a std::unique_lock, on the same mutex as used to protect the shared variable

http://en.cppreference.com/w/cpp/thread/condition_variable

I understand that by protecting the std::condition_variable with a mutex we are protected against missing a notify if the waiting thread is not actually waiting. Answered here already: Shared atomic variable is not properly published if it is not modified under mutex

What I would like to know is if it's possible to use the mutex only to protect the std::condition_variable, and some other form of protection for the shared data? If we modify the example given in the other answer, would this work?

std::atomic_bool proceed(false);
std::mutex m;
std::condition_variable cv;

std::thread t([&m,&cv,&proceed]()
{
    {
        std::unique_lock<std::mutex> l(m);
        while(!proceed) {
            hardWork();
            cv.wait(l);
        }
    }
});

proceed = true;

{
    std::lock_guard<std::mutex> lock(m);
}
cv.notify_one();
t.join();

Or is there something going on with memory ordering or caches that I have missed?


Update


I'm aware that the mutex is normally protecting the shared data as well, using the atomic variable was just an example. The question is not about how to protect the shared data, but if it's necessary to use the same mutex to protect both. Another example using a second mutex:

bool proceed(false);
std::mutex boolMutex;

std::mutex cvMutex;
std::condition_variable cv;
std::unique_lock<std::mutex> l(cvMutex);

void setBool()
{
    std::lock_guard<std::mutex> lock(boolMutex);
    proceed = true;
}

bool checkBool()
{
    std::lock_guard<std::mutex> lock(boolMutex);
    return proceed;
}

void worker()
{
    while (true)
    {
        cv.wait(l);
        if (checkBool()) {
            // Do work
            return;
        }
    }
}

int main()
{
    std::thread t(worker);
    setBool();

    {
        std::lock_guard<std::mutex> lock(cvMutex);
    }
    cv.notify_one();
    t.join();

    return 0;
}

回答1:


The mutex-protected flag must be set, and the condition variable get signalled, while the mutex is still being held:

{
    std::lock_guard<std::mutex> lock(m);
    proceed = true;
    cv.notify_one();
}

Furthermore, in this case the proceed flag does not need to be an atomic entity. A simple

bool proceed;

will be sufficient. With access to proceed happening only while holding the associated mutex, making proceed atomic accomplishes absolutely nothing.

atomic entities are for handling exotic concurrency situations that do not involve any mutexes in the first place.




回答2:


I don't think Sam`s answer is correct. Consider the following code:

// thread #1:
std::unique_lock<std::mutex> l(m);
while (!proceed) cv.wait(l);

// thread #2:
proceed = true; // atomic to avoid data race
cv.notify_one();

The problem here is the following possible sequence of events:

thread #1: while (!proceed) // evaluated as true
thread #2: proceed = true;
thread #2: cv.notify_one();
thread #1: cv.wait(l); // never gets notified

To avoid this scenario, a typical solution is to protect modification of proceed with the same mutex:

// thread #1:
std::unique_lock<std::mutex> l(m);
while (!proceed) cv.wait(l);

// thread #2:
{
   std::lock_guard<std::mutex> l(m);
   proceed = true; // does not need to be atomic
}
cv.notify_one();

Now, proceed = true; must happen either before while (!proceed) or after cv.wait(l); starts waiting; both is ok. In the first case, there is no waiting at all; in the second case, cv.notify_one(); is guaranteed to happen only when cv.wait(l); is actually waiting.

Now, what about your (kind-of academic) case?

// thread #1:
std::unique_lock<std::mutex> l(m);
while (!proceed) cv.wait(l);

// thread #2:
proceed = true; // atomic to avoid data race
{
   std::lock_guard<std::mutex> lock(m);
}
cv.notify_one();

I believe this case is also perfectly valid, since the above-described wrong scenario cannot happen as well. For simple reason. If while (!proceed) is evaluated as false, again, there is no waiting. And, if while (!proceed) is evaluated as true, then notification cannot happen until cw.wait(l); is invoked.

Conclusion

I believe your first example is ok and the quote from cppreference is incorrect.



来源:https://stackoverflow.com/questions/38185016/mutex-protecting-stdcondition-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!