#include #include #include typedef struct Account { int balance; pthread_mutex_t lock; pthread_cond_t condition; } Account; void account_init( Account *acc ) { acc->balance = 0; pthread_mutex_init( &acc->lock, NULL ); pthread_cond_init( &acc->condition, NULL ); } void account_destroy( Account *acc ) { pthread_mutex_destroy( &acc->lock ); pthread_cond_destroy( &acc->condition ); } void account_deposit( Account *acc, int d ) { pthread_mutex_lock( &acc->lock ); acc->balance += d; printf( "Deposit %d succeeds -- new balance is %d\n", d, acc->balance ); pthread_cond_broadcast( &acc->condition ); pthread_mutex_unlock( &acc->lock ); } void account_withdraw( Account *acc, int d ) { pthread_mutex_lock( &acc->lock ); while( acc->balance < d ) pthread_cond_wait( &acc->condition, &acc->lock ); acc->balance -= d; printf( "Withdraw %d succeeds -- new balance is %d\n", d, acc->balance ); pthread_mutex_unlock( &acc->lock ); } Account theAccount; void *withdraw( void * param ) { int dollars = (int) param; account_withdraw( &theAccount, dollars ); return NULL; } void *deposit( void * param ) { int dollars = (int) param; account_deposit( &theAccount, dollars ); return NULL; } int main( ) { account_init( &theAccount ); pthread_t t1, t2, t3, t4, t5; pthread_create( &t1, NULL, withdraw, (void *) 25 ); pthread_create( &t2, NULL, withdraw, (void *) 75 ); pthread_create( &t3, NULL, withdraw, (void *) 100 ); pthread_create( &t4, NULL, deposit, (void *) 20 ); sleep( 2 ); pthread_create( &t5, NULL, deposit, (void *) 180 ); pthread_join( t1, NULL ); pthread_join( t2, NULL ); pthread_join( t3, NULL ); pthread_join( t4, NULL ); pthread_join( t5, NULL ); pthread_exit( NULL ); return 0; }