/* tbarriertest Based on Robbins & Robbins */ #include #include #include #include "barrier.h" // Thread function void *printthread(void *arg) { // Linux uses unsigned long for pthread_t fprintf(stderr,"This is the first print of thread %lu\n", (unsigned long)pthread_self()); waitbarrier(); fprintf(stderr,"This is the second print of thread %lu\n", (unsigned long)pthread_self()); return NULL; } int main(int argc, char *argv[]) { int numThreads = 3; if (argc > 1) numThreads = atoi(argv[1]); pthread_t tids[numThreads]; // Set up a barrier for three threads. if (initbarrier(numThreads)) { fprintf(stderr,"Error initilizing barrier\n"); return 1; } // Set up the threads for (int i = 0; i < numThreads; ++i) { if (pthread_create(&tids[i], NULL, printthread, NULL)) fprintf(stderr,"Error creating thread %d.\n", i); } // Wait till they're done. for (int i = 0; i < numThreads; ++i) { if (pthread_join(tids[i], NULL)) fprintf(stderr,"Error joining thread %d.\n", i); } fprintf(stderr,"All threads complete.\n"); return 0; }