1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| #include<stdlib.h> #include<pthread.h> #include<stdio.h> int arr[10000]; typedef struct{ int Min; int Max; int sum; }Data; void* sum(void* args){ int i = 0; Data* p_data = (Data*)args; for(i = p_data->Min;i<p_data->Max;i++){ p_data->sum += arr[i]; } printf("%d\n",p_data->sum); return NULL; } int main(){ int i=0; for(i = 0;i<10000;i++){ arr[i] = rand() % 50; } pthread_t th1; pthread_t th2; Data d1 = { 0 , 5000 , 0 }; Data d2 = { 5000 , 10000 , 0 }; pthread_create(&th1,NULL,sum,&d1); pthread_create(&th2,NULL,sum,&d2); pthread_join(th1,NULL); pthread_join(th2,NULL); printf("answer is %d\n",d1.sum + d2.sum); return 0; }
|