#include #include #include #include /* the number of threads */ int num_threads; /* the function called for each thread */ void* worker(void* idp) { /* get our thread id */ int id = * (int*) idp; /* we start to work */ printf("Thread %d starting!\n", id); /* simulate the threads taking slightly different amounts of time by sleeping * for our thread id seconds */ sleep(id); printf("Thread %d is done its work!\n", id); /* TODO create a barrier here! */ printf("Thread %d is past the barrier!\n", id); 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); }