Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Condition variable usage pattern in C/C++ and other languages

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?

like image 909
vehsakul Avatar asked Nov 10 '22 05:11

vehsakul


1 Answers

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 waiting.

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.

like image 180
Tim B Avatar answered Nov 15 '22 06:11

Tim B