pi1.c: 使用2個線程根據萊布尼茲級數計算PI
? 萊布尼茲級數公式: 1 - 1/3 + 1/5 - 1/7 + 1/9 - ... = PI/4
? 主線程創建1個輔助線程
? 主線程計算級數的前半部分
? 輔助線程計算級數的后半部分
? 主線程等待輔助線程運行結束后,將前半部分和后半部分相加
實現思路:
用全局變量存儲主線程和副線程中的計算結果,然后將結果相加*4即得到結果。
#include<stdio.h>
#include<unistd.h>
#include<pthread.h>#define NUMBER 200double PI;
double worker_output;
double master_output;void *worker(void *arg){int i;double j;worker_output=0;for(i=1;i<=NUMBER;i++){j=i;if(i%2==0)worker_output-=1/(2*j-1);elseworker_output+=1/(2*j-1);}return NULL;
}void master(){int i=NUMBER+1;double j;master_output=0;for(;i<=2*NUMBER;i++){j=i;if(i%2==0)master_output-=1/(2*j-1);elsemaster_output+=1/(2*j-1);}
}int main(){pthread_t worker_tid;pthread_create(&worker_tid,NULL,worker,NULL);master();pthread_join(worker_tid,NULL);PI=(worker_output+master_output)*4;printf("PI: %f\n",PI);return 0;
}
歡迎留言交流。。。