#include #include #include #include //Global variables const int N=1000000; const int tNUM = 4; int array[1000000]; int count; //A shared variable that each thread will access //The mutex is declared globally pthread_mutex_t mp; //function prototypes int count3s(void); void *count3s_thread(void *); int main() { int i, result; pthread_mutex_init(&mp, NULL); // srand(time(0)); for (i = 0; i < N; i++) array[i] = rand()%100 + 1; result = count3s(); printf("There were %d 3's\n",result); // The mutex is no longer needed pthread_mutex_destroy(&mp); exit(0); } // This function creates tNUM threads int count3s(void) { int i; int thr_data[tNUM]; pthread_t thr[tNUM]; for (i = 0; i < tNUM; i++) { thr_data[i] = i; pthread_create(&thr[i], NULL, count3s_thread, (void *)&thr_data[i]); } /* block until all threads complete */ for (i = 0; i < tNUM; ++i) { pthread_join(thr[i], NULL); } return count; } // The funtion that each will execute void *count3s_thread(void *id) { // Compute the portion of the array that this thread should search int myid = *(int *)id, cnt3 = 0, i; int private_count = 0; int length_per_thread = N/tNUM; int start = myid * length_per_thread; for ( i = start; i < start + length_per_thread; i++) { if(array[i] == 3) private_count++; } // Acquire the mutex and add the threads count to the global count pthread_mutex_lock(&mp); count += private_count; pthread_mutex_unlock(&mp); }