#include #include #include /* the number of threads */ int num_threads; /* whose turn it is */ volatile int turn = 0; /* the function called for each thread */ void* worker(void* idp) { /* get our thread id */ int id = * (int*) idp; /* busy wait until it is our turn */ while (turn != id) ; /* our turn! */ printf("Thread %d says hello!\n", id); /* next thread's turn */ turn++; 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]); } /* an array of threads */ pthread_t threads[num_threads]; int ids[num_threads]; int i; /* 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); }