/* System V Semaphores and pthreads. */ #include #include #include #include #include #include #include "array.h" #define massert( cond, msg ) \ if( cond ) { \ perror( msg ); \ exit(-1); \ } #define TIME 1000000 char buf[] = "abcdefghijklmnopqrstuvwsyz"; pthread_mutex_t mut_main, mut_inv, mut_rev; void *inv( void *data ) { int len = strlen(buf); while( 1 ) { massert(pthread_mutex_lock(&mut_inv) != 0, "pthread_mutex_lock"); inverse(buf, len); usleep( TIME ); massert(pthread_mutex_unlock(&mut_main) != 0, "pthread_mutex_unlock"); } } void *rev( void* data ) { int len = strlen(buf); while( 1 ) { massert(pthread_mutex_lock(&mut_rev) != 0, "pthread_mutex_lock"); reverse(buf, len); usleep( TIME ); massert(pthread_mutex_unlock(&mut_main) != 0, "pthread_mutex_unlock"); } } int main( int argc, char* argv[] ) { pthread_t inv_pthread, rev_pthread; massert( pthread_mutex_init(&mut_main, NULL) != 0, "pthread_init_mutex"); massert( pthread_mutex_init(&mut_rev, NULL) != 0, "pthread_init_mutex"); massert( pthread_mutex_init(&mut_inv, NULL) != 0, "pthread_init_mutex"); massert(pthread_create( &inv_pthread, NULL, inv, NULL ) != 0, "pthread" ); massert(pthread_create( &rev_pthread, NULL, rev, NULL ) != 0, "pthread" ); while(1) { massert(pthread_mutex_unlock(&mut_inv) != 0, "pthread_mutex_lock"); massert(pthread_mutex_lock(&mut_main) != 0, "pthread_mutex_lock"); puts(buf); usleep( TIME ); massert(pthread_mutex_unlock(&mut_rev) != 0, "pthread_mutex_unlock"); massert(pthread_mutex_lock(&mut_main) != 0, "pthread_mutex_lock"); puts(buf); usleep( TIME ); } pthread_exit( NULL ); return 0; }