Skip to content

Commit 4532f81

Browse files
committed
^condition_variable_11
1 parent 1221359 commit 4532f81

File tree

1 file changed

+18
-10
lines changed

1 file changed

+18
-10
lines changed

cpp/11.cpp

Lines changed: 18 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -684,24 +684,32 @@ int lento(int a = 0)
684684
/// @endcond
685685

686686
/**
687-
https://en.cppreference.com/w/cpp/thread/condition_variable
687+
[condition_variable](https://en.cppreference.com/w/cpp/thread/condition_variable)
688+
[notify_one](https://en.cppreference.com/w/cpp/thread/condition_variable/notify_one)
688689
*/
689690

690691
void condition_variable_11()
691692
{
692693
mutex m;
693-
bool ready;
694+
int stage = 0;
694695
condition_variable cv;
695-
thread initiator([&m, &ready, &cv] {
696+
thread th(
697+
[&m, &stage, &cv] {
698+
unique_lock<mutex> lk(m);
699+
cv.wait(lk, [&stage] { return stage == 1; });
700+
stage = 2;
701+
lk.unlock();
702+
cv.notify_one();
703+
});
704+
// locking block
705+
{
696706
unique_lock<mutex> lk(m);
697-
lento();
698-
lk.unlock();
699-
ready = true;
700-
cv.notify_one();
701-
});
707+
stage = 1;
708+
}
709+
cv.notify_one();
702710
unique_lock<mutex> lk(m);
703-
cv.wait(lk, [&ready] { return ready; });
704-
initiator.join();
711+
cv.wait(lk, [&stage] { return stage == 2; });
712+
th.join();
705713
}
706714

707715
void threads_11()

0 commit comments

Comments
 (0)