
High-Level Language Constructs 95
Listing 5.1: Explicit locking to protect a critical section in C with POSIX
threads.
int sharedA , sha redB ;
p t h r e a d m u t e x t swapMutex ;
void ThreadBod y ( void * thread id ) {
int tmp ;
p t h r e a d m u t e x l o c k (& swapMutex );
tmp = sharedA ;
sharedA = shar edB + 4;
sharedB = shar edA - 2;
p t h r e a d m u t e x u n l o c k (& swapMutex );
pthread_ e xit ( NULL );
}
int main ( int argc , char ** argv ) {
/* ... */
p t h r e a d m u t e x i n i t (& swapMutex , NULL );
for ( t =0; t < N UM_THREADS ; t ++) {
rc = pthread_create (& threads [t ] , NULL ,
ThreadBody , ( void *) t );
if ( rc ) { /* ... */ }
}
for