#define _XOPEN_SOURCE 600 #include #include #include #include #include #include #include #include #include #include #define die(msg) {perror (msg); exit (EXIT_FAILURE); } sem_t sem; int stop; void sig_handler (int sig) { stop = sig; } void *thread1 (void *data) { int t = (int) data; while (!stop) { while (sem_wait (&sem) == -1 && errno == EINTR) continue; printf ("My name is %d. thread %d\n", t, t); fflush (stdout); sem_post (&sem); sleep (1); } return NULL; } void *thread2 (void *data) { int t = (int) data; while (!stop) { while (sem_wait (&sem) == -1 && errno == EINTR) continue; printf ("My name is %d. thread %d\n", t, t); fflush (stdout); sem_post (&sem); sleep (1); } return NULL; } void *thread3 (void *data) { int t = (int) data; while (!stop) { while (sem_wait (&sem) == -1 && errno == EINTR) continue; printf ("My name is %d. thread %d\n", t, t); fflush (stdout); sem_post (&sem); sleep (1); } return NULL; } void *thread4 (void *data) { int t = (int) data; while (!stop) { while (sem_wait (&sem) == -1 && errno == EINTR) continue; printf ("My name is %d. thread %d\n", t, t); fflush (stdout); sem_post (&sem); sleep (1); } return NULL; } int main (void) { pthread_t p1, p2, p3, p4; signal (SIGINT, sig_handler); stop = 0; if (sem_init (&sem, 0, 0) == -1) die ("sem_init"); pthread_create (&p1, NULL, thread1, (void *) 1); pthread_create (&p2, NULL, thread2, (void *) 2); pthread_create (&p3, NULL, thread3, (void *) 3); pthread_create (&p4, NULL, thread4, (void *) 4); while (!stop) { printf ("main\n"); fflush (stdout); sem_post (&sem); sleep (2); } sem_post (&sem); pthread_join (p1, NULL); pthread_join (p2, NULL); pthread_join (p3, NULL); pthread_join (p4, NULL); return 0; }