/* 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 SLEEP 1000000 char buf[] = "abcdefghijklmnopqrstuvwsyz"; pthread_rwlock_t lock; void *inv( ) { int len = strlen(buf); while( 1 ) { massert(pthread_rwlock_wrlock( &lock ) != 0, "pthread_rwlock_wrlock"); inverse(buf, len); massert(pthread_rwlock_unlock( &lock ) != 0, "pthread_rwlock_unlock"); usleep( SLEEP ); } } void *rev( ) { int len = strlen(buf); while( 1 ) { massert(pthread_rwlock_wrlock( &lock ) != 0, "pthread_rwlock_wrlock"); reverse(buf, len); massert(pthread_rwlock_unlock( &lock ) != 0, "pthread_rwlock_unlock"); usleep( SLEEP ); } } void *cnt( ) { int len = strlen(buf), ct; while( 1 ) { massert(pthread_rwlock_rdlock( &lock ) != 0, "pthread_rwlock_rdlock"); ct = count( buf, len); printf("%d\n", ct); massert(pthread_rwlock_unlock( &lock ) != 0, "pthread_rwlock_unlock"); usleep( SLEEP ); } } int main( int argc, char* argv[] ) { pthread_t inv_pthread, rev_pthread, cnt_pthread; massert(pthread_rwlock_init( &lock, NULL ) != 0, "pthread_rwlock_init"); massert(pthread_create( &inv_pthread, NULL, inv, NULL ) != 0, "pthread" ); massert(pthread_create( &rev_pthread, NULL, rev, NULL ) != 0, "pthread" ); massert(pthread_create( &cnt_pthread, NULL, cnt, NULL ) != 0, "pthread" ); while(1) { massert(pthread_rwlock_rdlock( &lock ), "pthread_rwlock_rdlock"); puts(buf); massert(pthread_rwlock_unlock( &lock ), "pthread_rwlock_unlock"); usleep( SLEEP ); } pthread_exit( NULL ); return 0; }