OSF DCE Application Development Guide--Core Components
Thread Concepts and Operations
• A nonrecursive mutex is locked only once by a thread, like a fast mutex. If the thread
tries to lock the mutex again without first unlocking it, the thread receives an error.
Thus, nonrecursive mutexes are more informative than fast mutexes because fast
mutexes block in such a case, leaving it up to you to determine why the thread no
longer executes. Also, if someone other than the owner tries to unlock a
nonrecursive mutex, an error is returned.
To lock a mutex, use one of the following routines, depending on what you want to
happen if the mutex is locked:
• The pthread_mutex_lock( ) routine
If the mutex is locked, the thread waits for the mutex to become available.
• The pthread_mutex_trylock() routine
If the mutex is locked, the thread continues without waiting for the mutex to become
available. The thread immediately checks the return status to see if the lock was
successful, and then takes whatever action is appropriate if it was not.
When a thread is finished accessing a piece of shared data, it unlocks the associated
mutex by calling the pthread_mutex_unlock( ) routine.
If another thread is waiting on the mutex, its execution is unblocked. If more than one
thread is waiting on the mutex, the scheduling policy and the thread scheduling priority
determine which thread acquires the mutex.
You can delete a mutex and reclaim its storage by calling the pthread_mutex_destroy( )
routine. Use this routine only after the mutex is no longer needed by any thread.
Mutexes are automatically deleted when the program terminates.
7.4.2 Condition Variables
A condition variable allows a thread to block its own execution until some shared data
reaches a particular state. Cooperating threads check the shared data and wait on the
condition variable. For example, one thread in a program produces work-to-do packets
and another thread consumes these packets (does the work). If the work queue is empty
when the consumer thread checks it, that thread waits on a work-to-do condition
variable. When the producer thread puts a packet on the queue, it signals the work-to-do
condition variable.
A condition variable is used to wait for a shared resource to assume some specific state
(a predicate). A mutex, on the other hand, is used to reserve some shared resource while
the resource is being manipulated. For example, a thread A may need to wait for a thread
B to finish a task X before thread A proceeds to execute a task Y. Thread B can tell
thread A that it has finished task X by using a variable they both have access to, a
condition variable. When thread A is ready to execute task Y, it looks at the condition
variable to see if thread B is finished (see Figure 7-3).
Figure 7-3. Thread A Waits on Condition Ready, Then Wakes Up and Proceeds
124245 Tandem Computers Incorporated 7−9