OSF DCE Application Development Guide--Core Components

OSF DCE Application Development Guide—Core Components
by another thread, the thread requesting the lock is blocked when it tries to lock the
mutex if you call pthread_mutex_lock( ) (see Figure 7-2). The blocked thread continues
and is not blocked if you call pthread_mutex_trylock( ).
Figure 7-2. Only One Thread Can Lock a Mutex
Thread B
var
mutex_var
lock block
Thread A
access
Each mutex must be initialized. (To initialize mutexes as part of the program’s one-time
initialization code, see Section 7.5.) To initialize a mutex, use the pthread_mutex_init( )
routine. This routine allows you to specify an attributes object, which allows you to
specify the mutex type. The following are types of mutexes:
A fast mutex (the default) is locked only once by a thread. If the thread tries to lock
the mutex again without first unlocking it, the thread waits for itself to release the
first lock and deadlocks on itself.
This type of mutex is called fast because it can be locked and unlocked more rapidly
than a recursive mutex. It is the most efficient form of mutex.
A recursive mutex can be locked more than once by a given thread without causing a
deadlock. The thread must call the pthread_mutex_unlock( ) routine the same
number of times that it called the pthread_mutex_lock( ) routine before another
thread can lock the mutex. Recursive mutexes have the notion of a mutex owner.
When a thread successfully locks a recursive mutex, it owns that mutex and the lock
count is set to 1. Any other thread attempting to lock the mutex blocks until the
mutex becomes unlocked. If the owner of the mutex attempts to lock the mutex
again, the lock count is incremented, and the thread continues running. When an
owner unlocks a recursive mutex, the lock count is decremented. The mutex remains
locked and owned until the count reaches 0 (zero). It is an error for any thread other
than the owner to attempt to unlock the mutex.
A recursive mutex is useful if a thread needs exclusive access to a piece of data, and
it needs to call another routine (or itself) that needs exclusive access to the data. A
recursive mutex allows nested attempts to lock the mutex to succeed rather than
deadlock.
This type of mutex requires more careful programming. Never use a recursive mutex
with condition variables because the implicit unlock performed for a
pthread_cond_wait( ) or pthread_cond_timedwait( ) may not actually release the
mutex. In that case, no other thread can satisfy the condition of the predicate.
7 8 Tandem Computers Incorporated 124245