/* Try number 3 using pthreads * works, performance boost compared to previous * attempt since we wait until all threes in section * have been found before acessing the global count * * compile with: * gcc count3s_parallel3.c -o count3s_parallel3 -pthread * * */ #include #include #include // changed by command line arg int num_threads = 1; // array to search - contains 9 threes #define arr_length 32 int arr[] = {2,3,0,2,3,3,1,0,0,1,3,2,2,3,1,0, 1,0,0,2,0,3,1,0,3,1,0,2,3,3,1,0}; // total of all threes found int count=0; // a private 3s counter for each thread #define MAX_THREADS arr_length int private_count[MAX_THREADS]; pthread_mutex_t m; // mutex to lock count while in use // args - long id void count3s_thread(void *id) { int i; // compute the portion of the array that this thread should // work on int length_per_thread = arr_length / num_threads; int start = (long)id * length_per_thread; //printf("Start from thread %d: %d\n", (long)id, start); for(i=start;i MAX_THREADS){ printf("Entered number > MAX_THREADS (%d)," "Defaulting to %d\n", MAX_THREADS, MAX_THREADS); num_threads = MAX_THREADS; } pthread_t threads[num_threads]; int rc; long t; // init the mutex if(pthread_mutex_init(&m, NULL) != 0) exit(EXIT_FAILURE); for(t=0; t