Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

locks and conditional variables:

22 views
Skip to first unread message

Doug Mika

unread,
Jul 24, 2015, 3:17:48 PM7/24/15
to
Hi to all, in the following program, would it be safe for me to remove the first line in the go() function (remove line: std::unique_lock<std::mutex> lck(mtx);)? Why do we need this line (ie why would we need to acquire the lock to change a boolean variable?)

// condition_variable example
#include <iostream> // std::cout
#include <thread> // std::thread
#include <mutex> // std::mutex, std::unique_lock
#include <condition_variable> // std::condition_variable

std::mutex mtx;
std::condition_variable cv;
bool ready = false;

void print_id (int id) {
std::unique_lock<std::mutex> lck(mtx);
while (!ready) cv.wait(lck);
// ...
std::cout << "thread " << id << '\n';
}

void go() {
std::unique_lock<std::mutex> lck(mtx);
ready = true;
cv.notify_all();
}

int main ()
{
std::thread threads[10];
// spawn 10 threads:
for (int i=0; i<10; ++i)
threads[i] = std::thread(print_id,i);

std::cout << "10 threads ready to race...\n";
go(); // go!

for (auto& th : threads) th.join();

return 0;
}

Melzzzzz

unread,
Jul 24, 2015, 3:41:41 PM7/24/15
to
On Fri, 24 Jul 2015 12:17:36 -0700 (PDT)
Doug Mika <doug...@gmail.com> wrote:

> Hi to all, in the following program, would it be safe for me to
> remove the first line in the go() function

Yes.

Chris M. Thomasson

unread,
Jul 24, 2015, 5:29:13 PM7/24/15
to
> "Melzzzzz" wrote in message news:20150724214131.2824a1ce@maxa-pc...
I think not, because a thread can miss a signal...

Think about the following scenario:
__________________________________________
void print_id (int id) {

std::unique_lock<std::mutex> lck(mtx);

while (!ready)
{
//HALT:
cv.wait(lck);
}
// ...
std::cout << "thread " << id << '\n';
}
__________________________________________

If a thread stalls in HALT, and the flag is then changed
to true and then a broadcast occurs, well, this thread
will miss that broadcast.

BAM! Deadlocked!

;^o

Melzzzzz

unread,
Jul 24, 2015, 5:40:58 PM7/24/15
to
Yes, I didn't thought about that, but in any way accesses to `ready`
have to be protected by same mutex.

0 new messages