DCE for the HP e3000 (B3821-90003)
44 Chapter5
Programming with Kernel Threads
Threads Synchronization and Communication
Threads Synchronization and Communication
All threads in a process execute within a single address space and share
resources. When threads share resources in an unsynchronized way,
incorrect output can result from race conditions or thread scheduling
anomalies. The Kernal Threads provide the following facilities and
routines to synchronize thread access to shared resources.
Mutexes (Mutual Exclusion Objects)
Mutexes are used to synchronize access by multiple threads to a shared
resource, allowing access by only one thread at a time. Routines for
creating and managing mutexes are:
• pthread_mutex_init(mutex,attr)
• pthread_mutex_destroy(mutex)
• pthread_mutex_lock(mutex)
• pthread_mutex_trylock(mutex)
• pthread_mutex_unlock(mutex)
Condition Variables
Condition variables provide an explicit communication vehicle between
threads. A condition variable is a shared resource, and requires a
mutex to protect it. A condition variable is used to block one or more
threads until a condition becomes true, then any or all of the blocked
threads can be unblocked. Routines for creating and managing
condition variables are:
• pthread_cond_init(cond,attr)
• pthread_cond_broadcast(cond)
• pthread_cond_signal(cond)
• pthread_cond_wait(cond,mutex)
• pthread_cond_destroy(cond)
Join Facility
The join facility is the simplest means of synchronizing threads, and
uses neither shared resources or mutexes. The join facility causes the
calling thread to wait until the specified thread finishes and returns a
status value to the calling thread. Routines for joining and detaching
threads are:
• pthread_join(thread,status)
• pthread_detach(thread)