Тёмный

Producer And Consumer Problem 

CppNuts
Подписаться 77 тыс.
Просмотров 36 тыс.
50% 1

JOIN ME
-----
RU-vid 🎬 / @cppnuts
Patreon 🚀 / cppnuts
COMPLETE PLAYLIST
------------
C++ Tutorial For Beginners: • Introduction To C++
STL (Standard Template Library): • STL In C++
ThreadIng In C++: • Multithreading In C++
Data Structures: • Data Structure
Algorithms: • Binary Search
Design Patterns: • Factory Design Pattern...
Smart Pointers: • Smart Pointer In C++
C++14: • Digit Separator In C++
C++17: • std string_view in C++...
C++ All Type Casts: • static_cast In C++
INTERVIEW PLAYLIST
------------
C++ Interview Q&A: • Structural Padding & P...
C++ Interview Q&A For Experienced: • How delete[] Knows How...
Linked List Interview Questions: • Find Kth Node From Bac...
BST Interview Questions: • Search Element In Bina...
Array Interview Questions: • Reverse An Array
String Interview Questions: • Check String Is Palind...
Bit Manipulation Questions: • Find Set Bit In Intege...
Binary Tree Interview Question: • Invert Binary Tree
Sorting Algorithms: • Bubble Sort
C++ MCQ: • Video
C MCQ: • What printf returns af...
C Interview Questions: • Designated Initializat...
QUICK SHORT VIDEOS
-------------
C++ Short : • C++ Short Videos
C Short : • Shorts C Programming MCQ
Producer Consumer OR Bounded Buffer Problem
THE PROBLEM STATEMENT:
1. Producer will produce and consumer will consume with synchronisation of a common buffer.
2. Until producer thread produces any data consumer thread can't consume.
3. Threads will use condition_variable to notify each other.
4. We need mutex if we use condition_variable because CV waits on mutex.
5. This is one of the example of producer consumer there are many.
PRODUCER thread steps:
1. lock mutex, if success then go ahead otherwise wait for mutex to get free.
2. check if buffer is full and if it is full then unlock mutex and sleep, if not then go ahead and produce.
3. insert item in buffer.
4. unlock mutex.
5. notify consumer.
CONSUMER thread steps:
1. lock mutex, if success then go ahead otherwise wait for mutex to get free.
2. check if buffer is empty and if it is, then unlock the mutex and sleep, if not then go ahead and consume.
3. consume item from buffer.
4. unlock mutex.
5. notify producer.
IMP:
Producer and Consumer have to notify each other upon completion of their job.
#threading #cpp #tutorial #programming #interviewquestions #softwareengineering #computerscience

Опубликовано:

 

5 окт 2024

Поделиться:

Ссылка:

Скачать:

Готовим ссылку...

Добавить в:

Мой плейлист
Посмотреть позже
Комментарии : 127   
@Pokemonbyv
@Pokemonbyv 4 года назад
Thanks for very clear explanation. One question As consumer thread is with infinite loop then how consumer thread would be close and main who is waiting for consumer thread to join will wait always?
@Sheetanshkumar
@Sheetanshkumar 3 года назад
Got the Job at Nutanix that too off campus because of your Multithreading videos. A huge Thanks to you. Appreciate you doing this for us. Thanks a lot.
@CppNuts
@CppNuts 3 года назад
Ohh that's great.. I feel so good, when i read something like this.. All the best dude..
@Sheetanshkumar
@Sheetanshkumar 3 года назад
@@CppNuts Seriously can't thank you much, just in one day before the interview I got to know about your channel and I learnt many things about Multithreading. ❤️ Please never stop making such videos, you're helping a lot.
@CppNuts
@CppNuts 3 года назад
Sure dude.. happy for you..
@gupta_nitin280
@gupta_nitin280 Год назад
@CppNuts, i think your solution works only if there is one consumer and one producer. let's assume this case:- there is one producer and two consumers and the buffer size is one. first, both consumers run and wait (both sleep because the buffer is empty initially). now the producer put the element in the buffer and wakes consumer1 and goes back to sleep because the buffer is full in the next iteration of while loop. now consumer1 runs and takes out the element and now wakes consumer2 instead of producer (because notify one gonna wake up any one thread). and now consumer2 sees the buffer empty and goes back to sleep now all three are sleeping and the program halts for eternity. solution for it is to never allow consumer to wake another consumer it means use two condition variables.
@CppNuts
@CppNuts Год назад
It is not about how many producer / consumers are there they all will have to lock the mutex before proceeding, so there can be any numbers of pro/con.
@alijohnnaqvi6383
@alijohnnaqvi6383 3 года назад
I would say you are the best teacher. Please keep helping us by making more this quality contents. Great man. May God bless you.
@CppNuts
@CppNuts 3 года назад
Thank you, I will
@liautraver3698
@liautraver3698 5 месяцев назад
this is the best intro to C++ threads I've found! Thank you!
@surkm9
@surkm9 4 года назад
Very well explained. But should have explained how to break the while (true) loop as well. Otherwise, thread will wait forever.
@CppNuts
@CppNuts 4 года назад
These systems are meant to run kind of forever.
@shahbazhusain5145
@shahbazhusain5145 8 месяцев назад
How to break the while loop , if there's no more data to consume because we are just putting our consumer thread to sleep here and not breaking the loop If I'll instruct something like this : int main(){ thread t1(producer, 100); thread t2(consumer); // thread t3(consumer); t1.join(); t2.join(); // t3.join(); cout
@sivaramboina9089
@sivaramboina9089 2 года назад
Seeing examples always give some insights on the topic. And this video helped me in that direction. Thank you.
@CppNuts
@CppNuts 2 года назад
Glad it was helpful!
@youshreyas1
@youshreyas1 3 года назад
Does locker.unlock(); require in producer() & consumer() ? because unique_lock() is used, which will take care of unlock in the block.
@stoka43
@stoka43 2 года назад
No, it is needed the due to notify_one() call. If you don't explicitly call the unlock function explicitly, you are going to call notify_one() while still having the lock
@ziyancheng8122
@ziyancheng8122 2 месяца назад
Not needed.
@mayankprabhakar5336
@mayankprabhakar5336 Месяц назад
Not needed bcz unique_lock destructor calls the unlock.
@kunalprasad1678
@kunalprasad1678 4 года назад
And one more thing I would like to ask you,can you please make a video on event and delegates ..I have read in c# but when it comes to c++ I get somewhat confused..you way of teaching is very good and makes things very easily to grab ..so it's a request ,if you can make a video on event and delegates,it will be really great..
@CppNuts
@CppNuts 4 года назад
Noted
@VoidloniXaarii
@VoidloniXaarii Год назад
I feel I'm not quite getting it yet but I must say this helped push me one small step further, thank you very much.. Also love how to say dude ❤
@renukaroy6529
@renukaroy6529 Год назад
your explanation is very nice🙂
@ratebuster4039
@ratebuster4039 3 года назад
Best and easiest explanation. Please also make one video for Thread Pool. Thanks.
@CppNuts
@CppNuts 3 года назад
Okay sure.. thanks..
@kiranchoudhary9730
@kiranchoudhary9730 3 года назад
Your explanation is bang on !! I would like to request you to create video on Semaphore
@saivivekvalluru1369
@saivivekvalluru1369 2 года назад
Really liked the video! Only thing I noticed as u are using deque it shud be pop_front() while consuming tht way consumer can take the first item producer produced.
@ChandraShekhar-by3cd
@ChandraShekhar-by3cd 4 года назад
After a long while , Finally most awaited Video .Thanks for the detailed explanation.How are you?.Please upload some video on System Design as there is not much best resources on this Important Area for Interview. I guess System Design under your guidance will help many of us..Thanks
@CppNuts
@CppNuts 4 года назад
Nice topic. Will try but will take time.
@ChandraShekhar-by3cd
@ChandraShekhar-by3cd 4 года назад
@@CppNuts Sure It will be worth waiting for another gen from YOU!!..Thanks
@CppNuts
@CppNuts 4 года назад
Thanks..
@sekarprem9172
@sekarprem9172 3 года назад
How to create the same program with any data type queue elements, how to use template in this same problem.
@debapriyoray9522
@debapriyoray9522 Год назад
Nice explanation. One thing I did not understand though, what is the need for calling the locker.unlock() function in both the functions? can someone please explain why we are calling the unlock() here and what would happen if we do not call the unlock()?
@CppNuts
@CppNuts Год назад
If you don't unlock then other thread won't be able to lock.
@chavhanshrihari3461
@chavhanshrihari3461 Год назад
Man.... You nailed it!!!. Amazing Bro. Learned many things from you.... God bless you and your family.
@stoka43
@stoka43 2 года назад
Thanks for the explanation, you gave me a clear idea of how to use condition variables and mutexes, but shouldn't we break the loop of the producer if the production is ended?
@CppNuts
@CppNuts 2 года назад
Actually the infinite loop shows that the work is keep on happening.
@stoka43
@stoka43 2 года назад
@@CppNuts I think that we can better synchronize the process using two semaphores, when to indicate empty slots and one to indicate occupied slots in the buffer.
@vivekrathi8462
@vivekrathi8462 6 месяцев назад
@CppNuts, we used unique_lock, but its inside the loop, so we had to unlock it manually. Is there any advantage of using unique_lock vs using normal mutex over here?
@get2himanshusingh
@get2himanshusingh 4 года назад
I did not understand why are you calling locker.unlock() for unique lock, because at the end mutex will be unlocked automatically due to unique lock once it goes out of scope
@UCSAnkitGirase
@UCSAnkitGirase 10 месяцев назад
I think because the unique_lock is in the while loop, we need to explicitly unlock the lock. Please let me know if you got the correct reason somewhere.
@chris52000
@chris52000 3 месяца назад
It’s because of the condition variable being notified. If you don’t unlock the lock, it means the thread waiting on the CV will likely have to immediately block on the mutex again. I think it would be a bit cleaner to release it via RAII instead though
@anujkumarjha9454
@anujkumarjha9454 4 года назад
beautifully explained.. nice work sir.
@CppNuts
@CppNuts 4 года назад
Thanks dude..
@veeru8432
@veeru8432 4 года назад
I have one doubt for this problem. Assume that, producer keep on producing and adding in to Buffer. Some how CPU not able to assign to Consumer thread. Buffer reaches 51 value, where as maxBufferSize is also 50. So condition will be false for cond.wait() --> line number 16 in producer thread. Now Producer will be in wait state, with unlocking mutex. then how will it notify consumer thread ?
@pavlosg.galiatsatos1984
@pavlosg.galiatsatos1984 4 года назад
Best explanation ever !!
@CppNuts
@CppNuts 4 года назад
Thanks sir..
@GiorgiAptsiauriX
@GiorgiAptsiauriX 4 года назад
Very clear. Your YT channel is bound to become very big. Keep grinding.
@umarteachestechwith2others803
@umarteachestechwith2others803 3 года назад
Best explanation. But I am confused here, will either producer or consumer execute notifyOne in every iteration?
@umarteachestechwith2others803
@umarteachestechwith2others803 3 года назад
if it is executing than it will be optimized solution here
@atulanand1587
@atulanand1587 4 года назад
we can you lock_gaurd here also right? using unique_lock we can notify so that consumers could get a lock..so it bit efficient I guess.
@shilpaaggarwal5008
@shilpaaggarwal5008 3 года назад
Condition variables work only on unique lock
@Krustachu
@Krustachu 3 года назад
very clear explanation! Thank you!
@srinu571
@srinu571 4 года назад
If I have ten threads which are waiting for same condition variable and the other thread calls notify_one() then which thread will wakeup out of these 10 threads ?
@therealpr0p
@therealpr0p 4 года назад
Any 1 of the remaining 9 (if all of them are either producers or consumers written like the one shown in the video). You can see that cond.wait is only after mutex is acquired.
@ak_gr_
@ak_gr_ Год назад
Great video. Should we not use here recursive_mutex since we are trying to lock mutex in a loop?
@t3ntube357
@t3ntube357 3 года назад
Finally I understand the puzzle, thank you teacher
@CppNuts
@CppNuts 3 года назад
😁
@kunalprasad1678
@kunalprasad1678 4 года назад
Is it possible to inform only a particular thread to consume...??
@vembukarthickt8809
@vembukarthickt8809 2 года назад
if the producer produced all elements at first and the thread would be destroyed(while loop would be over) and now the consumers consumed all the elements and buffer size became 0. It would wait for the producer to notify but producers would have been destroyed. what would the consumer thread do?
@praffullapandey146
@praffullapandey146 3 месяца назад
correct, producer should have some flag to denote that all the production is done. Consumer can check at the end of it work.
@jpou23
@jpou23 2 года назад
Hello, great video! Is there any reason to explicitly unlock in this example? I thought unlocking unique_locks was unnecessary.
@kshitijdwivedi5784
@kshitijdwivedi5784 Год назад
Yes, the unique_lock() automatically unlocks (releases) the mutex when it goes out of scope of the function. But, I think Rupesh have purposely unlocked here because, he wanted the lock to be acquired by the other party (consumer / producer) once one has done his job of producer or consuming. However, as soon as either of the cond.notify_one() is executed, the scope of current unique_lock() ends, and the mutex is unlocked for the other function. So, unlocking is unnecessary and the program will be fine, if you remove both of those locker.unlock() statements.
@priyalgarhwal2278
@priyalgarhwal2278 3 года назад
Nice video , but what is solution to problem ? How to solve it?
@LeelaseshuKumar
@LeelaseshuKumar 4 года назад
Hi Rupesh, thanks for uploaded producers and consumers problem. I have wrote each and every line in my machine. But it's not showing consumer part , only it's showing producer part 50th data only. I have waited too long but didn't happened anything.
@CppNuts
@CppNuts 4 года назад
Post you code plz.
@LeelaseshuKumar
@LeelaseshuKumar 4 года назад
@@CppNuts hi Rupesh. How to post my code here. Let me the way
@LeelaseshuKumar
@LeelaseshuKumar 4 года назад
// producerConsumer_problem.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include #include #include #include #include #include using namespace std; std::mutex mu; std::condition_variable cond; deque buffer; const unsigned int maxBufferSize = 50; void producer(int val){ while (val) { std::unique_lock locker(mu); cond.wait(locker,[](){return buffer.size() < maxBufferSize;}); buffer.push_back(val); cout
@LeelaseshuKumar
@LeelaseshuKumar 4 года назад
Hi Rupesh, can you check and give me , where i did mistake in the above code. if its running at your side, please tell me what is the issue. # thanks Rupesh you did too much good things. i have learned so many things from your cppnuts.
@CppNuts
@CppNuts 4 года назад
In consumer place buffer.size() > 0, that is the only wrong thing i guess.
@udaysingh7748
@udaysingh7748 4 года назад
Bhaiya when you will introduce Hashing in c++ Although u explained some part of hashing pls make vedio on it iam very curious about it
@CppNuts
@CppNuts 4 года назад
Yes I remember that I have talked about hashing in between videos but never explain hashing as a video topic. Will do it..
@vasantprabhu
@vasantprabhu 4 года назад
Some idea you can get during unordered set, unordered map
@ajayjadhav900
@ajayjadhav900 4 года назад
Great video... keep it up Could you please make a tutorial on lamba expression in c++ as it is very complex to read from book.
@CppNuts
@CppNuts 4 года назад
Yes, soon
@ajayjadhav900
@ajayjadhav900 4 года назад
@@CppNuts most of the people are waiting for it
@CppNuts
@CppNuts 4 года назад
Yaa sure..
@dheLLycocuq
@dheLLycocuq 4 года назад
Thanks man you really explained well.
@CppNuts
@CppNuts 4 года назад
Thanks man..
@SuperWhatusername
@SuperWhatusername 2 года назад
Thanks CppNuts
@NikashKumar
@NikashKumar 3 года назад
what tool or resource are u using to make ur videos ?
@KnowledgeMedia1
@KnowledgeMedia1 Год назад
Thanks a lot bro
@CppNuts
@CppNuts Год назад
Welcome dude
@kunalprasad722
@kunalprasad722 4 года назад
Can you please let us know how we can solve this problem?Putting sleep will work but there can be some better option i believe.
@CppNuts
@CppNuts 4 года назад
Like what?
@kunalprasad722
@kunalprasad722 4 года назад
@@CppNuts if we keep a sleep after the notify of producer thread,then producer thread will notify and will go to sleep instead of acquiring the mutex and thus the problem can be solved according to me.If I am wrong or not considering some case,please let me know.That will be great.
@pranavnyavanandi9710
@pranavnyavanandi9710 2 года назад
I knew from the thumbnail itself that this was going to be an Indian channel. 👍
@pitrya2533
@pitrya2533 8 месяцев назад
Nice explanation. I dont see a problem though.
@Артур-з6щ7э
@Артур-з6щ7э 3 года назад
Best explanation!
@CppNuts
@CppNuts 3 года назад
Glad it was helpful!
@shouryapratapbhadauriya2380
@shouryapratapbhadauriya2380 3 года назад
How can I use this in frame capturing in one thread and processing that frame in another thread and display it?
@CppNuts
@CppNuts 3 года назад
You can use Queue as critical section and start pushing from producer thread and consume images from consumer thread.
@shouryapratapbhadauriya2380
@shouryapratapbhadauriya2380 3 года назад
@@CppNuts as I am doing this there is a delay in consumer window
@gannuatharvan7988
@gannuatharvan7988 3 года назад
Good explanation but the code isn't terminating
@CppNuts
@CppNuts 3 года назад
There must be some issue please paste your code here.
@jamesdvc
@jamesdvc 4 года назад
Great video again! Good job mate!
@CppNuts
@CppNuts 4 года назад
Thanks again!
@shilpaaggarwal5008
@shilpaaggarwal5008 3 года назад
Why are you calling unlock on unique lock?
@shilpaaggarwal5008
@shilpaaggarwal5008 3 года назад
I guess it might be because locker is never going out of scope because of while loop. Hence it is never unlocking itself. So we have to unlock it manually...
@CppNuts
@CppNuts 3 года назад
It's unlocked bcoz others can lock same mutex.
@VikashKumar-uh4kx
@VikashKumar-uh4kx 3 года назад
@@CppNuts But it should get automatically unlocked in its destructor. Isn't it? Then why are we unlocking it explicitly. In unique lock video, you mentioned not too call unlock again. Could you please clarify?
@sharkzeeh
@sharkzeeh 4 года назад
show us main part pls
@wadewang574
@wadewang574 3 года назад
Does this has github code ?
@mohanp1245
@mohanp1245 5 месяцев назад
Sir can you explain when this program will get terminate?
@CppNuts
@CppNuts 5 месяцев назад
This is infinitely running code..
@chitranshsaxena59
@chitranshsaxena59 4 года назад
As usual, quality content
@CppNuts
@CppNuts 4 года назад
Thanks man!!
@priyaprasad6103
@priyaprasad6103 3 года назад
can u please share the code
@CppNuts
@CppNuts 3 года назад
Code is available at github, link you can get from channels about page.
@nachoImagine
@nachoImagine 4 года назад
Thanks!
@CppNuts
@CppNuts 4 года назад
Welcome!
@stephenscren4120
@stephenscren4120 4 года назад
can i get this coding ?
@amargandhi1137
@amargandhi1137 4 года назад
Nice awesome Eargaelly wating for thread safe in c++
@CppNuts
@CppNuts 4 года назад
I remember it.
@elhouarizohier3824
@elhouarizohier3824 Год назад
you'the G maaan 🔥
@liangzhang1722
@liangzhang1722 3 года назад
Thank yoU!
@CppNuts
@CppNuts 3 года назад
You're welcome!
@youshreyas1
@youshreyas1 3 года назад
Source Code If Anyone want to experiment: ----------- #include using namespace std; std::mutex mu; std::condition_variable cond; deque buffer; const unsigned int maxBufferSize = 50; bool done = false; void producer(int val) { std::thread::id my_id = std::this_thread::get_id(); // Get Thread ID cout
@narendranathjagarlamudi3191
@narendranathjagarlamudi3191 2 года назад
Thank you so much for the code!
@JaswinderSingh-dz1ui
@JaswinderSingh-dz1ui 11 месяцев назад
600 😀
@borisatud9853
@borisatud9853 6 месяцев назад
Why are you running the locker.unluck() methods, I thought the point of the wrapper class was to not need to explicitly do that.
Далее
Sleep VS Wait In Threading
10:17
Просмотров 18 тыс.
Timed Mutex In C++
11:50
Просмотров 27 тыс.
ВЫЖИЛ В ДРЕВНЕМ ЕГИПТЕ!
13:09
Просмотров 211 тыс.
Find The Real MrBeast, Win $10,000
00:37
Просмотров 22 млн
Producer - Consumer Problem in Multi-Threading
25:18
Просмотров 113 тыс.
why do header files even exist?
10:53
Просмотров 411 тыс.
Harder Than It Seems? 5 Minute Timer in C++
20:10
Просмотров 172 тыс.
Weak Pointer In C++
16:47
Просмотров 26 тыс.
What is Mutex in C++ (Multithreading for Beginners)
12:29
promise And future In C++
8:24
Просмотров 37 тыс.
Mutex In C++
16:22
Просмотров 107 тыс.
Join And Detach In C++
17:15
Просмотров 65 тыс.
I gave 127 interviews. Top 5 Algorithms they asked me.
8:36