Along with mutexes, pthreads gives us another tool for synchronization between the threads, condition variables.
Condition variables are variables of the kind pthread_cond_t.
When a thread is waiting on a mutex it will continuously keep polling on the mutex waiting for it to get unlocked. Such behavior could lead to wastage of CPU resources. This can be prevented by using the condition variables.
The condition variables can be initialized statically
or dynamically
Attribute can be left NULL if default attributes are sufficient. The only attribute condition variables have is process_shared, which indicates that the condition variable is visible to threads of other processes too.
Now to use the condition variable in a thread we have two functions
This is called when a thread wants to wait for specific task to be completed by another thread before continuing its operations. This function should be called after locking the mutex, which automatically gets unlocked once the thread goes in to wait state.
This function does the job of signaling to the thread that had called pthread_cond_wait. Note that the "condition variable" used in the signal and the wait functions should be the same. We need to lock the mutex that is shared by the threads before calling this function and unlock it after the call.
Once pthread_cond_signal is called the threas which was waiting on the function pthread_cond_wait will proceed with its execution.
The following program depicts the use of condition variables.
We create two threads
"fill": which fills values into an array "arr"
read: Which reads the values of the array.
Now we can read from the array unless it is not filled, thus the thread read calls pthread_cond_wait, waiting for the array to be filled. On the other hand the thread "fill" calls pthread_cond_signal once it is done filling the array.Thus making sure that the threads are in synchronization.
Save the program as pthread_cond.c, and compile using -lpthread flag
Execute the program
Thus we can see that the read thread was waiting until the fill thread did not call the signal, and only after receiving the signal the read thread continued execution.
Hello, sorry, but I see some problems in this article. 1. In most cases this frase not correct: "When a thread is waiting on a mutex it will continuously keep polling on the mutex waiting for it to get unlocked", couse if thread wait mutex - then this thread sleep until scheduler wake up this thread. 2. Posix enable return from pthread_cond_wait() even if condwar doesn't changed, for this reason I reccomend use code from here https://www.opennet.ru/docs/RUS/linux_parallel/node75.html.
ReplyDelete