- Declare and initialize global data/variables which require synchronization (such as "count")
- Declare and initialize a condition variable object
- Declare and initialize an associated mutex
- Create threads A and B to do work
Step for thread A:
- Lock the mutex
- 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.
- Get the signal from thread B and wake up. After waking up, the thread will automatically grab the mutex.
- Unlock the mutex and proceed.
Step for thread B:
- Lock the mutex
- 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.
- Unlock the mutex and proceed.
See Also: POSIX Threads Programming
No comments:
Post a Comment