#include #include #include #include static sem_t sem[2]; static long count[2]; static void *func(void *arg) { long my_id = (long) arg; for (;;) { sem_wait(&sem[my_id]); count[my_id]++; sem_post(&sem[1-my_id]); } return NULL; } int main(void) { void *ret; pthread_t t1, t2; sem_init(&sem[0], 0, 1); sem_init(&sem[1], 0, 0); pthread_create(&t1, NULL, func, (void*) 0); pthread_create(&t2, NULL, func, (void*) 1); sleep(2); pthread_cancel(t1); pthread_cancel(t2); pthread_join(t1, &ret); pthread_join(t2, &ret); printf("count=%ld\n", count[0] + count[1]); return 0; }