Condition Variable in Modern cpp and unique lock | Introduction to Concurrency in C++

  Рет қаралды 13,173

Mike Shah

Mike Shah

Күн бұрын

►Full Series Playlist: • Modern C++ (cpp) Concu...
►Find full courses on: courses.mshah.io/
►Join as Member to Support the channel: / @mikeshah
►Git Repo: github.com/MikeShah/moderncpp...
►Lesson Description: In this lesson I teach you about how to use a condition_variable in C++. This is a relatively old concept that is useful for making sure that cpu time is not wasted attempting to constantly 'try' to acquire a lock.
00:00 Synchronization of threads with locks
1:20 Wasted cpu cycles waiting
1:58 Introduction to condition variable
3:20 What is needed for condition variables
4:21 Worker and reporter thread idea
5:00 Implementation of condition variable
5:45 Setting up condition variable
6:30 Setting up our 2 threads
7:20 Setting up worker thread
8:07 Using a unique_lock
9:20 Doing work in reporter thread and updating condition
10:50 notify with condition variable
11:58 Setting up reporting thread
12:46 Condition variable wait
13:20 wait blocks a thread
14:04 notify wakes up a thread
14:34 Syntax fixes
15:08 Logic fixes
15:40 Successful execution of program
16:10 Explanation again of what we have done
►KZfaq Channel: / mikeshah
►Please like and subscribe to help the channel!

Пікірлер: 31
@nithinga4386
@nithinga4386 Жыл бұрын
Thanks for this, from this base I improved the code by adding infinite loops and scoped locks so that they communicate indefinitely, which is more a common used case
@MikeShah
@MikeShah Жыл бұрын
Cheers!
@not_ever
@not_ever 8 ай бұрын
I think there is a bug here. if(!notified) should be while(!notified) in case of spurious wakeups. As it said in the cppreference documentation for wait, the predicate version of wait is equivalent to: while (!stop_waiting()) { wait(lock); } Have I misunderstood something ? It's quite likely I have, as I haven't written multithreaded C++ for a couple of years and I'm watching these videos to refresh my memory.
@MikeShah
@MikeShah 8 ай бұрын
Agreed, I think this is a bug in the video and my Code. This I think has been updated on cppreference as well (it's possible my interpretation was a bug as well)
@srikarv4358
@srikarv4358 Жыл бұрын
Thanks for the tutorial video, Mike. Feedback on the example program: I ran into the issue of "lost wakeup" with condition variables while trying out this.
@simoneckerstorfer4174
@simoneckerstorfer4174 2 жыл бұрын
thanks for making those videos!
@MikeShah
@MikeShah 2 жыл бұрын
You are most welcome! A few more trickling into this series in the next few weeks :)
@MonsterZack5
@MonsterZack5 2 жыл бұрын
I enjoyed this video, thank you for making it.
@MikeShah
@MikeShah 2 жыл бұрын
You are most welcome!
@user-jm5wu7yk8p
@user-jm5wu7yk8p 8 ай бұрын
Thank you this video helped me understand
@MikeShah
@MikeShah 8 ай бұрын
Cheers!
@barbuceanu2005
@barbuceanu2005 Ай бұрын
After notify_one, the reporter thread tries to re-aquire the lock, but it is already locked by the worker thread (until the lock goes out of scope). If the lock would not go out of scope in the worker thread, a lock.unlock() would be needed before (or after) notify_one(), in order to allow the reporter thread to re-aquire the lock after wait, otherwise the reporter thread would remain blocked.
@EschoolIsrael
@EschoolIsrael 2 жыл бұрын
Hi Mike , this example similar to many examples out there , i think the idea of conditional variable is where the thread not finished , and have while (true) or while (m_running) than you need to use the unlock and lock of the unique lock, so this example need to be advanced little more.
@MikeShah
@MikeShah 2 жыл бұрын
I suppose an example using say a producer/consumer where the producers and consumers have infinite loops waiting for items to be placed on a queue (or spaces available on the queue for a producer) would be another good example to use conditional variables :)
@VardaanNarang
@VardaanNarang 3 ай бұрын
Hi Mike! The series is great. My only request would be to create a video on std::promise.
@MikeShah
@MikeShah 3 ай бұрын
Cheers! Check out this video on futures: kzfaq.info/get/bejne/atqnfadmyuDPkZs.html that may be helpful!
@chomandengnya
@chomandengnya 9 ай бұрын
Hi MIke, this seems to work without the notified boolean variable. Although does that mean the reporter thread keeps on polling our conditional variable?
@MikeShah
@MikeShah 9 ай бұрын
Yes, I think some folks have noted that below.
@Popart-xh2fd
@Popart-xh2fd 3 ай бұрын
What happens if the thread_worker finishes without notify_one?
@thestarinthesky_
@thestarinthesky_ Жыл бұрын
Thanks Mike for this great series! I have a question: If a thread that is blocked on a std::condition_variable is notified, but the lock on the associated mutex has not been released and let’s say the lock is going to be released 10 seconds later, would the waiting thread wait for the lock to be released or the situation would be undefined?
@MikeShah
@MikeShah Жыл бұрын
Should remain blocked on the lock if I understand the question correctly: en.cppreference.com/w/cpp/thread/condition_variable condition_variable needs a unique_lock
@thestarinthesky_
@thestarinthesky_ Жыл бұрын
@@MikeShah Thank you.
@antonfernando8409
@antonfernando8409 Жыл бұрын
Just as when I got 2 threads hung, your video shows up 😀. Can you think of a case where 2 mutexes might be needed in your example. I ask that, as my worker thread calls lock via unique lock, as the reporter thread starts and takes the lock, it seems lock is called on a locked mutex, which is undefined behavior. The worker lock call followed by cv wait, so if predicate is false the mutex will be unlocked for reporter to grab it. So could the case where worker condition is met so lock is held, meantime report tries to grab is resulting in UB. I am reluctant to use 2 mutex solutions, it makes no sense, here mutex with cv is used to protect shared data, can done with 1 mutex. But how to prevent locking a locked mutex. Thanks Mike
@MikeShah
@MikeShah Жыл бұрын
Two mutexes tend to show up in patterns like producer/consumer or readers/writers problems. If you have some intermediate data structure where data is being stored you might want to use some condition variable to flag when data is ready for instance.
@macewindont9922
@macewindont9922 24 күн бұрын
Wouldn't the code be simpler if you eliminate the `notified` boolean? Can't you just always let the worker signal to the reporter thread, instead of filtering it with the boolean?
@MikeShah
@MikeShah 23 күн бұрын
We do need some variable to store state for condidtional variables, just one of the pieces needed.
@kowalski2031
@kowalski2031 8 ай бұрын
the notified variable seems useless in this code
@macewindont9922
@macewindont9922 24 күн бұрын
It seems like a slight optimization that eliminates the need to wait if the second thread has already finished.
@JakubH
@JakubH 4 ай бұрын
shouldn't the `result` and `notified` variables be marked as volatile?
@MikeShah
@MikeShah 4 ай бұрын
I'll need to think about that. To be honest, volatile is difficult to use correctly, but for 'signaling' type of applications it is likely useful.
@solomonpizzocaro2999
@solomonpizzocaro2999 Жыл бұрын
result = 42... (unintentional I guess haha)
How Many Balloons Does It Take To Fly?
00:18
MrBeast
Рет қаралды 30 МЛН
Was ist im Eis versteckt? 🧊 Coole Winter-Gadgets von Amazon
00:37
SMOL German
Рет қаралды 36 МЛН
When You Get Ran Over By A Car...
00:15
Jojo Sim
Рет қаралды 23 МЛН
Khó thế mà cũng làm được || How did the police do that? #shorts
01:00
Лекция 4. Condition variables. Алгоритмы синхронизации
1:10:18
Should I pass by const reference or by value?
10:45
The Cherno
Рет қаралды 99 М.
Using a trylock | Introduction to Concurrency in C++
18:30
Mike Shah
Рет қаралды 3,2 М.
C++ Multi Threading Part 2: Mutex And Conditional Variables
44:43
31 nooby C++ habits you need to ditch
16:18
mCoding
Рет қаралды 741 М.
[C++11] STL: Coundition Variable - Прерывание потоков
11:36
C++ Coroutines, from Scratch - Phil Nash - CppCon 2022
59:22
Klavye İle Trafik Işığını Yönetmek #shorts
0:18
Osman Kabadayı
Рет қаралды 956 М.
Clicks чехол-клавиатура для iPhone ⌨️
0:59
Игровой Комп с Авито за 4500р
1:00
ЖЕЛЕЗНЫЙ КОРОЛЬ
Рет қаралды 2,1 МЛН
Красиво, но телефон жаль
0:32
Бесполезные Новости
Рет қаралды 350 М.
После ввода кода - протирайте панель
0:18
Up Your Brains
Рет қаралды 1,2 МЛН
Собери ПК и Получи 10,000₽
1:00
build monsters
Рет қаралды 2,4 МЛН