#include #include #include #include //Global variables const int N=1000000; const int tNUM = 4; int array[1000000]; int count[4]; //function prototypes int count3s(void); void *count3s_thread(void *); int main() { int i, result; // srand(time(0)); for (i = 0; i < N; i++) array[i] = rand()%100 + 1; result = count3s(); printf("There were %d 3's\n",result); exit(0); } // This function creates tNUM threads int count3s(void) { int i; int thr_data[tNUM]; int countt = 0; 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); countt += count[i]; } return countt; } // 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 length_per_thread = N/tNUM; int start = myid * length_per_thread; for ( i = start; i < start + length_per_thread; i++) if(array[i] == 3) cnt3++; count[myid] = cnt3; pthread_exit(NULL); }