

Ret=pthread_create(&thread_id1,NULL,&read,NULL) Ret=pthread_create(&thread_id,NULL,&fill,NULL) Pthread_cond_wait(&cond_var,&fill_mutex) Pthread_cond_t cond_var=PTHREAD_COND_INITIALIZER 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. 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. Read: Which reads the values of the array. "fill": which fills values into an array "arr"

The following program depicts the use of condition variables. Once pthread_cond_signal is called the threas which was waiting on the function pthread_cond_wait will proceed with its execution. We need to lock the mutex that is shared by the threads before calling this function and unlock it after the call. Note that the "condition variable" used in the signal and the wait functions should be the same. This function does the job of signaling to the thread that had called pthread_cond_wait. This function should be called after locking the mutex, which automatically gets unlocked once the thread goes in to wait state. This is called when a thread wants to wait for specific task to be completed by another thread before continuing its operations. Now to use the condition variable in a thread we have two functions The only attribute condition variables have is process_shared, which indicates that the condition variable is visible to threads of other processes too. Pthread_cond_t cond_var=PTHREAD_COND_INTIALIZERĪttribute can be left NULL if default attributes are sufficient. The condition variables can be initialized statically This can be prevented by using the condition variables. Such behavior could lead to wastage of CPU resources. When a thread is waiting on a mutex it will continuously keep polling on the mutex waiting for it to get unlocked. Along with mutexes, pthreads gives us another tool for synchronization between the threads, condition variables.Ĭondition variables are variables of the kind pthread_cond_t.
