+ 1
Producer consumer | not working
Hi Could you please help me understand why below code is not working : https://code.sololearn.com/cA139a7A40A1/?ref=app
6 ответов
+ 2
After going through a tutorial and according to my understanding I added the following lines at the end in both functions:
in produce function
------------
l.lock();
cv.wait(l,[] {return is produced==false;});
in consumer function
-------------
cv.notify_one();
I think it works fine now!
+ 1
Thanks a lot Abhay for helping me out...
I did put condition variable in consume only and missed in produce function.... Now wait and notify is done in both the function which makes it work fine now
However I am getting confuse on l.lock in produce function you are suggesting but not in consume ... Why so ? Also is it require to lock explicitly as wait doesn't ensure locking ? If required, why it is working without locking in both function as well ?
Once again thanks for helping
+ 1
Ketan Lalcheta locking was necessary in produce as cv.wait is to be performed inside critical section only as you are doing now (i am not sure what global variable is effected when you execute cv.wait outside lock but it needs to be performed inside cs.) .
But I don't understand what you meant by "wait doesn't ensure locking"!
+ 1
Ketan Lalcheta sorry for responding late but i honestly don't have an understanding of lock.guard and other much stuff .
Also isn't unique lock creating a lock and so your code is definitely working by locking wait inside that unique lock, as well that notify is just hinting other code to wake again, not really anything to change globally so keeping it outside of lock or inside lock shudn't matter much I think !
But if you really wanna know more about your doubts, you can just open a new question :).
0
I thought unique lock is ensuring locking mechanism like we get on case of lock.guard
I mean lock is effective when object of unique lock is created... Difference between this with lock guard is that it goes on hold through wait and it has unlock also
Also why my code updated is working without locking just due to wait and notify is confusing me more on usage of lock before wait
0
Cannot take wait outside lock...two reasons:
1. it does affect the global bool variable
2. Wait method needs lock object which in turn created by mutex
However, many thanks for making my code working