
3.8 Semaphores and Locks in Pthreads
Mutex locks are part of the Pthreads (POSIX1.c) standard.
Semaphores are not a part of Pthreads, but are in POSIX1.b.
3.8.1 Mutex
A Pthreads mutex is a lock with behavior similar to that of a Win32
CRITICAL_SECTION.
Operations pthread_mutex_lock() and pthread_mutex_unlock() are analogous to
EnterCriticalSection() and LeaveCriticalSection(), respectively:
A thread that calls pthread_mutex_lock() on a mutex is granted access to the mutex if
no other thread owns the mutex; otherwise the thread is blocked.
A thread that calls pthread_mutex_lock() on a mutex and is granted access to the
mutex becomes the owner of the mutex.
A thread releases its ownership by calling pthread_mutex_unlock(). A thread calling
pthread_mutex_unlock() must be the owner of the mutex.
There is a conditional wait operation pthread_mutex_trylock(pthread_mutex_t*
mutex) that will never block the calling thread.
o If the mutex is currently locked, then the operation returns immediately with the
error code EBUSY.
o Otherwise, the calling thread becomes the owner.
Listing 3.27 shows how to use a Pthreads mutex.
You initialize a mutex by calling the pthread_mutex_init() function. The first
parameter is the address of the mutex. If you need to initialize a mutex with non-
default attributes, the second parameter can specify the address of an attribute object.
When the mutex is no longer needed, it is destroyed by calling
pthread_mutex_destroy().
#include <pthread.h>
pthread_mutex_t mutex;
void* Thread1(void* arg) { void* Thread2(void* arg) {
pthread_mutex_lock(&mutex); pthread_mutex_lock(&mutex);
/* critical section */ /* critical section */
pthread_mutex_unlock(&mutex); pthread_mutex_unlock(&mutex);
return NULL; return NULL;
} }
int main() {
pthread_t threadArray[2];// array of thread IDs
int status; // error code
pthread_attr_t threadAttribute; // thread attribute
// initialize mutex
status = pthread_mutex_init(&mutex,NULL);
if (status != 0) { /* See Listing 1.4 for error handling */ }
// initialize the thread attribute object
status = pthread_attr_init(&threadAttribute);
if (status != 0) { /* … */}
// set the scheduling scope attribute
status = pthread_attr_setscope(&threadAttribute,
PTHREAD_SCOPE_SYSTEM);
if (status != 0) { /* … */}
// Create two threads and store their IDs in array threadArray
status = pthread_create(&threadArray[0], &threadAttribute, Thread1, (void*) 1L);
if (status != 0) { /* … */}
status = pthread_create(&threadArray[1], &threadAttribute, Thread2, (void*) 2L);
if (status != 0) { /* … */}
status = pthread_attr_destroy(&threadAttribute); // destroy attribute object
if (status != 0) { /* … */}
// Wait for threads to finish
status = pthread_join(threadArray[0],NULL);
if (status != 0) { /* … */}
status = pthread_join(threadArray[1],NULL);
if (status != 0) { /* … */}
// Destroy mutex
status = pthread_mutex_destroy(&mutex);
if (status != 0) { /* … */ }
}
Listing 3.27 Using Pthreads mutex objects.