#include #include #include #include /* the number of threads */ int num_threads; /* a semaphore for each thread */ sem_t* semaphores; /* the function called for each thread */ void* worker(void* idp) { /* get our thread id */ int id = * (int*) idp; /* wait for our semaphore to become unlocked */ sem_wait(&semaphores[id]); /* do our work */ printf("Thread %d says hello!\n", id); /* unlock the semaphore belonging to the next thread (unless last) */ if (id < (num_threads - 1)) { sem_post(&semaphores[id + 1]); } pthread_exit(NULL); } int main (int argc, char** argv) { /* get the number of threads */ if (argc < 2) { printf("Pass the number of threads to use!\n"); pthread_exit(0); } else { num_threads = atoi(argv[1]); } sem_t s[num_threads]; semaphores = s; /* initialize the semaphores to 0 */ int i; for (i = 0; i < num_threads; i++) { sem_init(&semaphores[i], 0, 0); } /* unlock thread 1 */ sem_post(&semaphores[0]); /* an array of threads */ pthread_t threads[num_threads]; int ids[num_threads]; /* spawn all threads */ for (i = 0; i < num_threads; i++) { ids[i] = i; pthread_create(&threads[i], NULL, worker, &ids[i]); } /* join all threads */ for (i = 0; i < num_threads; i++) { pthread_join(threads[i], NULL); } pthread_exit(0); }