If you look at documentation describing the usage of condition variables (cv), you'll see that e.g. in PThreads and C++ you don't need to hold the mutex of a cv to call notify on this cv. Whereas e.g. in Java and Python, you must lock the mutex to do the same thing.
Is there some deep reason why things are implemented this way (I'm about the latter case), given that an implementation of a language like Java eventually uses some native threading tools?
The Java notify
and notifyAll
basic synchronization tools both require you to synchronize on the object before calling them. This is for a simple safety point since it also requires you to synchronize on them before wait
ing.
For example if you have two threads. One thread reads data from a buffer and one thread writes data into the buffer.
The reading data thread needs to wait until the writing data thread has finished writing a block of data into the buffer and then it can read the block.
If wait()
, notify()
, and notifyAll()
methods can be called without synchronization then you can get a race condition where:
The reading thread calls wait()
and the thread is added to waiting queue.
At the same time, the writing thread calls notify()
to signal it has added data.
The reading thread misses the change and waits forever since the notify()
was processed before the wait()
was.
By forcing the wait
and notify
to happen within a synchronized block this race condition is removed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With