#include #include #include #include #include int threads = 0; struct threadinfo { int name, randomiser, delay; pthread_t id; pthread_mutex_t * semaphore; }; void * background(void * a) { threads += 1; threadinfo * info = (threadinfo *)a; for (int i=0; irandomiser; i+=1) random(); for (int i=1; i<20; i+=1) { pthread_mutex_lock(info->semaphore); printf("%c%d ", info->name, i); fflush(stdout); if (info->name!='A' || i%2==1) pthread_mutex_unlock(info->semaphore); usleep(random() % info->delay); } threads -= 1; return NULL; } int main() { pthread_mutex_t sem; pthread_mutex_init(& sem, NULL); threadinfo a, b; a.name='A'; a.randomiser=7; a.delay = 1000000; a.semaphore = & sem; b.name='B'; b.randomiser=3; b.delay = 333333; b.semaphore = & sem; pthread_create(& a.id, NULL, background, & a); pthread_create(& b.id, NULL, background, & b); void * x; pthread_join(a.id, & x); pthread_join(b.id, & x); printf("done\n"); }