Thursday, January 11, 2007

Pthreads Semaphore

senaphore.h 提供的 semaphore 實作。

#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>

void *runner( void* );
void critical_sleep( int );

sem_t mutex;

int main(){
 pthread_t t1, t2;
 int r1, r2;

 sem_init( &mutex, 0, 1 );

 r1 = 1;
 r2 = 2;
 pthread_create( &t1, NULL, runner, &r1 );
 pthread_create( &t2, NULL, runner, &r2 );
 pthread_join( t1, NULL );
 pthread_join( t2, NULL );
 return 0;
}

void * runner( void * p ){
 int *id = (int*) p;
 printf( "thread %d: started\n", *id );
 critical_sleep( *id );
 printf( "thread %d: terminated\n", *id );
}

void critical_sleep( int id ){
 printf( "thread %d: entering critical_sleep()\n", id );
 sem_wait( &mutex );
 printf( "thread %d: entered critical_sleep()\n", id );
 printf( "thread %d: 1 sec sleeping\n", id );
 sleep( 1 );
 printf( "thread %d: leaving critical_sleep()\n", id );
 sem_post( &mutex );
 printf( "thread %d: left critical_sleep()\n", id );
}

參考資料

No comments: