Showing posts with label multithread. Show all posts
Showing posts with label multithread. Show all posts

Thursday, June 16, 2011

Something about conditional variables in PThread

Step to use conditional variables:
  1.  Declare and initialize global data/variables which require synchronization (such as "count")
  2. Declare and initialize a condition variable object
  3. Declare and initialize an associated mutex
  4. Create threads A and B to do work
Step for thread A:
  1. Lock the mutex
  2. Check the global data (e.g., counter), if not fulfilled, call pthread_cond_wait(). pthread_cond_wait() will automatically release the lock and put the thread into block state.
  3. Get the signal from thread B and wake up. After waking up, the thread will automatically grab the mutex.
  4. Unlock the mutex and proceed.
Step for thread B:
  1. Lock the mutex
  2. modify the global data (e.g., counter), if certain threshold is met, call pthread_cond_signal() or pthread_cond_broadcast to notify the blocked thread(s). pthread_cond_singal() is for one thread and pthread_cond_broadcast() assume there are multiple threads waiting. 
  3. Unlock the mutex and proceed.