1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <pthread.h> 4 #include <sys/types.h> 5 #include <dirent.h> 6 #include <errno.h> 7 #include <unistd.h> 8 9 pthread_barrier_t bar; 10 11 12 void* tester(void *arg) 13 { 14 struct dirent en, *enp; 15 DIR *d = opendir("/"); 16 int r; 17 18 if (d == NULL) { 19 perror("opendir() failed"); 20 return NULL; 21 } 22 23 pthread_barrier_wait(&bar); 24 25 do { 26 r = readdir_r(d, &en, &enp); 27 if (errno != 0) 28 { 29 perror("thread tester error"); 30 exit(2); 31 break; 32 } 33 } while (enp != NULL); 34 35 closedir(d); 36 } 37 38 void* checker(void *arg) 39 { 40 pthread_barrier_wait(&bar); 41 printf("Passed barrier!\n"); 42 } 43 44 45 int main(int argc, char *argv[]) 46 { 47 int i, ret, nthreads; 48 pthread_t *threads; 49 pthread_t th; 50 51 if (argc <= 1) 52 { 53 printf("Need one argument\n"); 54 exit(1); 55 } 56 57 nthreads = atoi(argv[1]); 58 threads = malloc(sizeof(pthread_t) * (nthreads + 1)); 59 if (threads == NULL) { 60 fprintf(stderr, "malloc failed!\n"); 61 exit(3); 62 } 63 64 printf("Trying with %d threads\n", nthreads); 65 66 if ( (ret = pthread_barrier_init(&bar, NULL, nthreads + 1)) != 0) 67 { 68 printf("error occurred during pthread_barrier_init, ret = %d\n", ret); 69 perror("Or: "); 70 exit(1); 71 } 72 73 printf("Creating checker thread\n"); 74 pthread_create(&th, NULL, checker, NULL); 75 76 printf("Creating tester threads\n"); 77 78 79 for (i = 0; i < nthreads; i++) { 80 ret = pthread_create(&threads[i], NULL, tester, NULL); 81 if (ret != 0) 82 threads[i] = 0; 83 } 84 85 //sleep(5); 86 87 printf("Starting join\n"); 88 for (i = 0; i < nthreads; i++) { 89 if (threads[i] != 0) 90 pthread_join(threads[i], NULL); 91 } 92 93 printf("All done!\n"); 94 return 0; 95 } 96