Condition variables in C

  Рет қаралды 94,961

CodeVault

CodeVault

Күн бұрын

Пікірлер: 179
@CARDSSerus
@CARDSSerus 3 жыл бұрын
I'm sure this gets said a lot, but this pthread playlist has legitimately helped me more than a semester of class. Thank you
@benjangel
@benjangel 4 ай бұрын
I cannot describe my gratitude my man. Solid high quality teaching. You're being loved from Turkiye.
@sirnosedevoid2282
@sirnosedevoid2282 3 жыл бұрын
This cleared up so much for me. Thank you very much for posting this!
@GeistPatrick
@GeistPatrick 3 жыл бұрын
Just great explanation! Can't wait till I got some time to watch your other content. :)
@fussball48
@fussball48 3 жыл бұрын
Thank you, I hope it will help my in my exam tomorrow, I will let you know
@fussball48
@fussball48 3 жыл бұрын
I passed, wonderful explanations, thank you
@martinparidon9056
@martinparidon9056 3 ай бұрын
Thank you for this video. It was presented very cleary and understandably.
@legonerd162
@legonerd162 2 жыл бұрын
Thank you, this was the only good explanation of condition variables i could find. Very well explained
@AndreFerreira-jv3qy
@AndreFerreira-jv3qy 3 ай бұрын
Great video man im learning so much from you thank you!
@zeobora
@zeobora Жыл бұрын
I'll only say just one word: Perfect!
@timjack5312
@timjack5312 Жыл бұрын
It is good for us to learn the concepts and implementation of the linux c!! Thank you!!
@eduardoestevakremer712
@eduardoestevakremer712 3 жыл бұрын
Thanks for this video. Your conceptual explanation is crystal clear !!
@planetis-m6066
@planetis-m6066 3 жыл бұрын
Great video, thank you for sharing! I think it's better to unlock the mutex after signaling the condition variable. Again many thanks!
@CodeVault
@CodeVault 3 жыл бұрын
I was actually curious on that topic and researched a bit. As it turns out, it doesn't really matter. You'd think that, because of the multithreaded nature of the program, there's a chance another thread would lock the mutex right after the unlock and right before the lock inside pthread_cond_wait. While it can happen, that's why we do a check every time we get past the pthread_cond_wait. Additionally, even if we have the order reversed (first signal then unlock), there's a chance another thread locks the mutex right after we call pthread_cond_signal. So either way, you can run in the same issue. Maybe you have another reason for it that I overlooked
@lin1450
@lin1450 3 жыл бұрын
Dude, you're amazing! Thank you so much!
@onursimsek6094
@onursimsek6094 3 жыл бұрын
Excellent example, excellent content. Thank you.
@leonardomaia7661
@leonardomaia7661 2 жыл бұрын
Thank you!! you did what my teacher couldn't
@leodriesch
@leodriesch 3 жыл бұрын
Great example and great explanation. Thanks!
@bisratw
@bisratw 2 жыл бұрын
What if we put the mutex lock after the while loop, instead of using condition variable?
@narasarajv5278
@narasarajv5278 3 жыл бұрын
Nice explanation Thank you...
@nachumdanzig
@nachumdanzig 2 жыл бұрын
Great Instructional Videos. Very helpful. Question: Could you have also solved the problem by putting the Mutex lock AFTER you check that fuel is above 40? Then the car would not lock the mutex unless there was enough fuel. With one car this would work.
@CodeVault
@CodeVault 2 жыл бұрын
No. That would cause a race condition on the fuel variable. You have to lock the mutex before checking simply because some threads might try to write to that fuel variable in the meantime. So, you must make sure, no other threads are currently trying to write to it.
@deepakr8261
@deepakr8261 10 ай бұрын
Thanks for the great video. Quick question, shouldn't the condition variable be signalled and then the mutex be released? If there is priority inheritance due to holding the mutex, we still hold the elevated priority while signalling the condition variable but if we do release of mutex first, then the inherited priority would get lost and our thread may get pre-empted out before getting a chance to signal the condition variable.
@CodeVault
@CodeVault 8 ай бұрын
It was so long ago, I don't fully remember. I tested the difference between the two and, in practice, didn't see a difference
@alejandroglez769
@alejandroglez769 2 жыл бұрын
Thank you very much for these videos, you have helped me a lot.
@rhodesiaFarmer
@rhodesiaFarmer Жыл бұрын
Awesome explanation
@happycode4478
@happycode4478 3 жыл бұрын
Thank you!! Great help for my operating systems class
@sagivalia5041
@sagivalia5041 2 жыл бұрын
Is it possible to pass an array of function pointers, kinda like this thread is doing this series of jobs or before joining pass it another function? EDIT: I tried passing a struct thread_jobs with the job count and a pointer to a function pointer and initialized the struct with an array of function pointers made on the stack of main, passed the struct as an argument and it successfully serialized a series of jobs for each thread. ofc, the function pointer's return type and args are static but as a POC it works.
@mastermax7777
@mastermax7777 10 ай бұрын
9:40 why do we have to lock something when we are checking ? like Couldnt we put line 21 right after the while() loop?
@CodeVault
@CodeVault 10 ай бұрын
Because, even when reading a variable a race condition could occur. If one process would write and our process would read then, we would be reading old data. And, if by chance, the writing process writes to that variable right after checking it then we would encounter a race condition and our program would be doing something completely unexpected
@gepeto3185
@gepeto3185 6 ай бұрын
Can you explain me why signal doesnt notify cond_wait in each iteration and waits for loop to end and then notifies cond_wait?Through examples that happens most of the time.
@CodeVault
@CodeVault 5 ай бұрын
It's because we already have locked the mutex and we only unlock it after the loop ends
@milee105
@milee105 11 ай бұрын
very helpful, thank you very much :D
@Toccobass13
@Toccobass13 2 жыл бұрын
So helpful, thank you
@jacobov3890
@jacobov3890 3 жыл бұрын
Better quality than my university classes. -__-
@yixianwang863
@yixianwang863 3 жыл бұрын
Thank you!
@1905xcimbom
@1905xcimbom 2 жыл бұрын
If I need different number of mutex'es depending on the input, how can I create mutexes?
@CodeVault
@CodeVault 2 жыл бұрын
You can simply have an array: pthread_mutex_t mutexes[100]; And just init and destroy them as needed: pthread_mutex_init(&mutexes[0], NULL); pthread_mutex_destroy(&mutexes[0], NULL);
@DINO5551000
@DINO5551000 2 жыл бұрын
How do you make sure your signal isn't sent, and then a thread executes wait and has to wait forever because it missed the signal that was sent previously.
@CodeVault
@CodeVault 2 жыл бұрын
Usually you don't have to since the condition is being checked before waiting
@DINO5551000
@DINO5551000 2 жыл бұрын
@@CodeVault I think I should elaborate some more. I think you misinterpret what I meant. What if the thread, that executes the signalling, does so before the other thread even has a chance to acquire the mutex and execute the line with the while and the wait? Wouldn't it mean that the thread executing the wait just missed the signal and is now stuck in an endless loop again? I mean the order of execution of threads in the os is arbitrary as far as I've understood it. Is there any specific reason as to why the situation I just described couldn't happen? Would be really thankful if you could help me understand this
@CodeVault
@CodeVault 2 жыл бұрын
@@DINO5551000 Yes, something like that could actually happen. The signal in that case would get "lost". Although, the important thing to note in the example I showed is we'll only call pthread_cond_wait when there isn't enough fuel. So, in our case, the thread would not need the signal and would simply skip over the while loop entirely. Sorry for the late reply
@deepikadeepika5169
@deepikadeepika5169 2 жыл бұрын
Very helpful !
@georgesudeep4622
@georgesudeep4622 2 жыл бұрын
I think I would've understood it better with a better example, because I got lost somewhere in the example. Thanks for the content though.
@rivermoon6159
@rivermoon6159 Жыл бұрын
thanks very much. Really saves my ass
@frnz1s
@frnz1s 3 жыл бұрын
Genius teaching!
@luisloureiro4059
@luisloureiro4059 2 жыл бұрын
hello, this helped me a lot. I just have a simple question, why do you need to lock and unlock the mutex in pthread car function if there is only one thread going in that function? I thought that mutex_lock and mutex_unlock are only for not letting 2 threads going into the same variable at same time. I still have the same result if i dont have this lock and unlock in car function. Is that a real problem or am i missing something?
@CodeVault
@CodeVault 2 жыл бұрын
The fuel variable can be changed simultaneously in the fuel_filling method by another thread. This can create a race condition
@luisloureiro4059
@luisloureiro4059 2 жыл бұрын
@@CodeVault Ohhh wait you re right. Thank you very much!
@elizavetaterente2127
@elizavetaterente2127 2 жыл бұрын
Thank you so much omg
@GAMEVUEG
@GAMEVUEG 3 жыл бұрын
I love you bro, are you a teacher ? You are explaining this better than mine
@CodeVault
@CodeVault 3 жыл бұрын
No, I don't teach at any university or school. I just learned by helping a lot of people throughout the years
@laurah.6241
@laurah.6241 2 жыл бұрын
Hi :) i've got a question about the condition variable: why can't I just put the while loop around the lock and the unlock, so each iteration the mutex would get unlocked and the thread for the fuel filling can lock the mutex and increase the fuel variable?
@CodeVault
@CodeVault 2 жыл бұрын
This might create an infinite loop since you'd be constantly locking and unlocking the mutex on that thread and not giving any chance for other threads to use it, thus, the fuel value never changing and continuing the loop
@ManishKumar-ez4gt
@ManishKumar-ez4gt Жыл бұрын
time to buy new clothes
@amrhesham2260
@amrhesham2260 3 жыл бұрын
thank you, keep going
@karangupta431
@karangupta431 3 жыл бұрын
nice explanation
@beingnikhil155
@beingnikhil155 3 жыл бұрын
Hey whats your name? I realy liked your accent and the way you explain
@CodeVault
@CodeVault 3 жыл бұрын
Sergiu.
@ciri_beat1242
@ciri_beat1242 2 жыл бұрын
il capo
@ArkFreestyle
@ArkFreestyle 3 жыл бұрын
Thank you so much, these are the highest quality C tutorials on youtube. Very underrated channel, you're an excellent teacher, please continue teaching!
@trevorjoel2150
@trevorjoel2150 3 жыл бұрын
I dont mean to be offtopic but does someone know of a method to get back into an Instagram account? I was dumb lost my password. I appreciate any help you can offer me!
@samuellionel4364
@samuellionel4364 3 жыл бұрын
@Trevor Joel instablaster :)
@trevorjoel2150
@trevorjoel2150 3 жыл бұрын
@Samuel Lionel Thanks for your reply. I found the site through google and I'm waiting for the hacking stuff atm. Looks like it's gonna take a while so I will get back to you later with my results.
@karangupta431
@karangupta431 3 жыл бұрын
My college teachers should teach like you , our lives would be fantastic then
@mustafakarakas1116
@mustafakarakas1116 2 жыл бұрын
16:35 The difference between pthread_cond_signal() and pthread_cond_broadcast() lies in what happens if multiple threads are blocked in pthread_cond_wait(). With pthread_cond_signal(), we are simply guaranteed that at least one of the blocked threads is woken up; with pthread_cond_broadcast(), all blocked threads are woken up.
@elenakalla
@elenakalla 3 жыл бұрын
I think you have the best teaching skills I've seen in all my school and University years. Thanks for educating us!
@playertwo9895
@playertwo9895 3 жыл бұрын
Sergiu, I can't thank you enough for this video. My OS professor really struggled to explain this topic, so I left the class without any intuition as to why condition variables were needed. Your example at 8:16 made my jaw drop, furthermore, your description of signalling being an indication that a condition's result *may* have changed really cleared things up for me. This is the second video of yours that I've watched (the first being pthread Barriers). It's safe to say that I'll be subscribing to your channel. Thank you for sharing your knowledge of these complex topics, you make them much easier to understand, and for that I'm grateful.
@playertwo9895
@playertwo9895 Жыл бұрын
I was looking at concurrency stuff again earlier today and remembered this video. Just wanted to say thanks again, I've since graduated and have been working at a big tech company :)
@chriscosta8806
@chriscosta8806 3 жыл бұрын
I have been searching since yesterday on condition variables so i can understand what they are exactly and how they work, and i can say it's the most helpful thing! Cheers from Cyprus keep on the good work.
@BankruptGreek
@BankruptGreek 3 жыл бұрын
lmao I am also from Cyprus are you studying on ucy?
@priyeshtandel2101
@priyeshtandel2101 Жыл бұрын
what an example !!🙂
@tas9214
@tas9214 2 жыл бұрын
Really glad I found this channel, the examples are always on point and a concept that seemed abstract previously makes perfect sense now!
@alejandrovesga7736
@alejandrovesga7736 Жыл бұрын
I frickin love u
@elkhoukhi
@elkhoukhi 3 жыл бұрын
You are an awesome teacher! keep on these tutorials coming :)) a question: is this the concept of producer/consumer? as I understand in this case, producer is the fuelFilling and the consumer is the car, right?
@CodeVault
@CodeVault 3 жыл бұрын
I guess you can say that. Usually it has to do with entities in the sense that producers create entities that consumers have to process. Here you only have a number. Here's the video on the producer/consumer problem: code-vault.net/lesson/tlu0jq32v9:1609364042686
@Noel_VI
@Noel_VI Жыл бұрын
I'm new to C, trying my best to learn the language to the fullest. But I'm having a hard time learning these concepts, I feel like I'm missing something. So if possible, can anyone please tell me of roadmap to C that I should follow? I appreciate the effort that went into this video.
@CodeVault
@CodeVault Жыл бұрын
The concepts taught in this video are a bit more advanced. I suggest starting out with a simple pet project that you evolve over time. It could a simple calculator that uses the terminal for user input/output or some sort of simple game. Once you have worked a bit with these you can come back to these videos and possibly improve your project
@Noel_VI
@Noel_VI Жыл бұрын
Thanks for the response, much appreciate it.
@homailot2378
@homailot2378 3 жыл бұрын
Thank you for the video! One question, however, isn't it better for the call to pthread_cond_signal to be on a thread that owns the mutex, meaning calling pthread_cond_signal before unlocking? The man page recommends this for a more predictable scheduling. Thank you again.
@CodeVault
@CodeVault 3 жыл бұрын
I actually researched this a bit and, from what I can tell, it really doesn't matter in this case because the the only thread that could unlock this mutex is the one we are signaling. In cases where you have some external thread that uses that mutex without the condition variable then, yes, it would be recommended to do so since the signaled thread would have a bigger chance of locking the mutex than the external ones. But all in all, it wouldn't impact the correctness of the code.
@homailot2378
@homailot2378 3 жыл бұрын
@@CodeVault thank you for taking your time to respond, and for the response as well!
@saularaya2066
@saularaya2066 3 ай бұрын
Piola👍
@blackplaydoh3522
@blackplaydoh3522 3 жыл бұрын
Classic consumer - producer problem, I would much rather see you solve it as an endless simulation (constantly fueling cars and when fuel too low in the main tank -> fill it up again;
@asinegaasinega
@asinegaasinega 3 жыл бұрын
this is so so so good. usually, guys are speaking way fast because they don't understand that it's hard to follow the concepts for someone brand new being exposed to the subject. you really have a gift for teaching. People think just because they know a subject matter that they can become teachers but that's is not true. It takes special skills to be able to relate a material to someone else that is brand new to the matter at hand. Just a million thanks
@SandwichMan
@SandwichMan 3 жыл бұрын
Got a final in 2 days and this was an aspect of synchronization which has been confusing me all semester. Very helpful.
@bilalbayrakdar7100
@bilalbayrakdar7100 3 жыл бұрын
clear explanation with simple example, thank you for creating such helpful content
@mikicerise6250
@mikicerise6250 3 жыл бұрын
I 'cond' wait to start practising with pthread_cond. I'll be here all week folks. ;)
@jawwad4020
@jawwad4020 3 күн бұрын
You're the c++ boss!
@Bladermishal10
@Bladermishal10 3 жыл бұрын
Big brain explaination. thank you
@egeergul3548
@egeergul3548 Жыл бұрын
thank you !! Great example!! Helpfull very helpfulllll
@onlyfootball6609
@onlyfootball6609 Жыл бұрын
The best video on this topic, best wishes for you!
@jiaqimike7114
@jiaqimike7114 2 жыл бұрын
Thank you, it is usefully for my collage work.
@kayakMike1000
@kayakMike1000 Жыл бұрын
I would rather know how they work rather than what they do.
@dobariyavraj3659
@dobariyavraj3659 11 ай бұрын
God sends the Savior, He's the One
@mehdicharife2335
@mehdicharife2335 3 жыл бұрын
Great content bro. You must be very smart to be able to come up with these great examples. Do you know where I can find some problems to practice this?
@CodeVault
@CodeVault 3 жыл бұрын
I don't have a special website. But it's easy to come up with one. Just think about a "resource" that can be "used" by many and can be replenished by many others. That's basically it.
@ubbe9263
@ubbe9263 8 ай бұрын
Great video! Thanks!
@matteopisati9966
@matteopisati9966 2 жыл бұрын
Thank you great job!
@ArvindDevaraj1
@ArvindDevaraj1 Жыл бұрын
amazing explanation
@אריאלצידון
@אריאלצידון 2 жыл бұрын
The best tracher i ever have..
@anamikakumari4311
@anamikakumari4311 2 жыл бұрын
You are the life changer
@guillaume6373
@guillaume6373 2 жыл бұрын
Great explanation!
@kotravaijm250
@kotravaijm250 2 жыл бұрын
you are a life saver
@suneelabbigari
@suneelabbigari 2 жыл бұрын
Shall we use the same pthread_mutex_t for two different processes as well ?? Do we have a different mutex for process also ?? Help me on this. When ever i search for it, all the blogs/sites are talking about pthread_mutex_t alone.
@CodeVault
@CodeVault 2 жыл бұрын
It's a bit more tricky. You will have to first add this flag to the mutex: pthread_mutexattr_setpshared(&attrmutex, PTHREAD_PROCESS_SHARED); and share the created mutex between the process (with mmap) Here's a StackOverflow response: stackoverflow.com/questions/20325146/share-condition-variable-mutex-between-processes-does-mutex-have-to-locked-be
@kaal_bhairav_23
@kaal_bhairav_23 3 жыл бұрын
you're the best
@trocandobytes
@trocandobytes Жыл бұрын
You're amazing. Thank you so much for share this knowledge.
@karinanosenko4907
@karinanosenko4907 3 жыл бұрын
Great tutorial
@tinewildiers4618
@tinewildiers4618 3 жыл бұрын
when will the second part of this video be up? great explanation
@CodeVault
@CodeVault 3 жыл бұрын
It's already up ;) You can check it out on our website: code-vault.net/lesson/18ec1942c2da46840693efe9b5203fac I don't usually name things "part 2" so that others searching for this topic will still find that video useful.
@tinewildiers4618
@tinewildiers4618 3 жыл бұрын
@@CodeVault thanks alot
@MichaelSoulier32Pens
@MichaelSoulier32Pens Жыл бұрын
What about protecting the fuel integer from being cached in any of the cpu caches? I don't think a mutex is sufficient for that, and I'm told that volatile is not enough either.
@CodeVault
@CodeVault Жыл бұрын
You don't have to worry about this issue. CPUs already handle synchronization primitives (such as semaphores, condition variables, mutexes ... ) in such a way that their cache will be consistent with memory. Whenever a write occurs to the fuel integer it invalidates all the other cores' caches for that variable's value
@pandasoli6581
@pandasoli6581 9 ай бұрын
There's no difference in the execution if I don't lock the mutex before the while loop. Do you see not locking it as a possible problem?
@CodeVault
@CodeVault 8 ай бұрын
Yes. It could cause a race condition after reading the fuel value the value could have changed before executing the code inside the while loop
@indrajeetdevre1296
@indrajeetdevre1296 Жыл бұрын
THank you
@basitsaeed9705
@basitsaeed9705 3 жыл бұрын
very helpful
@karthiks2687
@karthiks2687 3 жыл бұрын
Hello can you teach me with client server connection program using threads in C..I have been asked to do an assignment of it..could you help me
@CodeVault
@CodeVault 3 жыл бұрын
I will look into this topic in the future
@saitcanbaskol9897
@saitcanbaskol9897 2 жыл бұрын
Amazing.
@SebastianPerez-jz9tk
@SebastianPerez-jz9tk Жыл бұрын
So good
@Codality
@Codality 2 жыл бұрын
Master
@srikonijeti
@srikonijeti 2 жыл бұрын
what happening if thread count to wake up car method increase ? when I tried your code with more threads to car method and its hang ,not sure reason....
@CodeVault
@CodeVault 2 жыл бұрын
Try increasing the loop in the fuel_filling function. Since that function, with 5 iteration, only fills 5 * 15 = 75 units of fuel while, you need 40 for each car
@bisratw
@bisratw 2 жыл бұрын
What if we put the mutex lock after the while loop, instead of using condition variable?
@CodeVault
@CodeVault 2 жыл бұрын
I'm not sure exactly what you mean. You cannot lock the same mutex twice. If you lock/unlock, you could theoretically achieve the same result but it would consume a lot of resources for no reason
@VasaMusic438
@VasaMusic438 2 жыл бұрын
Great lesson, but with some schemes or drawings it would be much understandable ;-)
@CodeVault
@CodeVault 2 жыл бұрын
Yep, whenever I can I'll add them. Thanks for the feedback!
@sunwoodad
@sunwoodad 2 жыл бұрын
7:18 Why car() cannot consume the fuel while fuel_filling() is in sleep?
@CodeVault
@CodeVault 2 жыл бұрын
It should be able to as fuel_filling() just unlocked the mutex before calling sleep()
@kira7641
@kira7641 Жыл бұрын
Great video but how would a car use fuel while it's filling 😂
@CodeVault
@CodeVault 11 ай бұрын
Maybe they left the AC on :D
@mya23compu
@mya23compu Жыл бұрын
You have successfully explained something that my professors, articles online, a textbook, and documentation couldn't explain well. And concisely too! These videos are amazing, please make more!
@NineInchFailz
@NineInchFailz Жыл бұрын
got your videos opened in one window and VS in another window working my CS 344 final assignment. My guy, you're the reason i'm passing.
@abdulrahmansafwat1555
@abdulrahmansafwat1555 10 ай бұрын
Thank You! I have been struggling with this whole concept and then found your video! Well explained! :)
@MyLifeMyWorld08
@MyLifeMyWorld08 3 жыл бұрын
Awesome explanation ! Thanks
Introduction to semaphores in C
12:24
CodeVault
Рет қаралды 125 М.
iPhone or Chocolate??
00:16
Hungry FAM
Рет қаралды 39 МЛН
Amazing Parenting Hacks! 👶✨ #ParentingTips #LifeHacks
00:18
Snack Chat
Рет қаралды 22 МЛН
Остановили аттракцион из-за дочки!
00:42
Victoria Portfolio
Рет қаралды 3,7 МЛН
Стойкость Фёдора поразила всех!
00:58
МИНУС БАЛЛ
Рет қаралды 3,3 МЛН
Being Competent With Coding Is More Fun
11:13
TheVimeagen
Рет қаралды 81 М.
WHY did this C++ code FAIL?
38:10
The Cherno
Рет қаралды 259 М.
why do void* pointers even exist?
8:17
Low Level
Рет қаралды 366 М.
Is Computer Science still worth it?
20:08
NeetCodeIO
Рет қаралды 335 М.
Producer - Consumer Problem in Multi-Threading
25:18
CodeVault
Рет қаралды 113 М.
Making an Algorithm Faster
30:08
NeetCodeIO
Рет қаралды 81 М.
Dynamic Programming isn't too hard. You just don't know what it is.
22:31
DecodingIntuition
Рет қаралды 154 М.
What are Race Conditions?
13:09
CodeVault
Рет қаралды 92 М.
Harder Than It Seems? 5 Minute Timer in C++
20:10
The Cherno
Рет қаралды 171 М.
Naming Things in Code
7:25
CodeAesthetic
Рет қаралды 2,1 МЛН
iPhone or Chocolate??
00:16
Hungry FAM
Рет қаралды 39 МЛН