#include #include #define NUM_THREADS 5 struct { pthread_mutex_t mutex; /* protexts access to value */ int value; /* Access protected by mutex */ } data = { PTHREAD_MUTEX_INITIALIZER, 0 }; void *thread( void *t_id ) { int i; for ( i = 0; i < 200; ++i ) { pthread_mutex_lock( &data.mutex ); ++data.value; printf( "thread %d: data value = %d\n", t_id, data.value ); pthread_mutex_unlock( &data.mutex ); } pthread_exit( NULL ); } int main() { pthread_t threads[ NUM_THREADS ]; int rc, t; for ( t = 0; t < NUM_THREADS; t++ ) { printf( "Creating thread %d\n", t ); pthread_create( &threads[ t ], NULL, thread, ( void * ) t ); } pthread_exit( NULL ); }