題目:
多進程:
#include <unistd.h> #include <stdio.h> #include <stdlib.h> #define n 100000000.0 int main() { int fd[2]; // 創建二個 fd, fd[0] 管道用於讀, fd[1] 管道用於寫 pipe(fd); // 創建進程 pid_t pid; for(int i = 0; i < 8; ++i) { pid = fork(); if(pid == 0) { double sum = 0.0; for(int j = (int)(i*(n/8)); j < (int)((i+1)*(n/8)); j++) { double temp = (4 / (1 + ((j + 0.5)/n)*((j + 0.5)/n)))*(1.0/n); sum += temp; } write(fd[1], &sum, sizeof(double)); exit(0); } } //計算求和 double ans = 0.0; for(int i = 0; i < 8; ++i) { double temp; read(fd[0], &temp, sizeof(double)); ans += temp; } printf("the ans is %.20lf\n", ans); return 0; }
多線程:
#include <stdlib.h> #include <unistd.h> #include <stdio.h> #include <fcntl.h> #include <string.h> #include <assert.h> #include <sys/types.h> #include <sys/stat.h> #include <pthread.h> void * sumpi1(void * arg); void * sumpi2(void * arg); double * pret; double * pret1; double ret,ret1; int main() { //定義兩個線程標識符 pthread_t pthread1, pthread2; //兩個線程退出后的返回值 void * thread1_return; void * thread2_return; //判斷線程創建成功否 int check_create; //判斷線程退出成功否 int check_end; double ans = 0.0; double n = 10000000.0; // 創建兩個線程 check_create = pthread_create(&pthread1, NULL, sumpi1, (void *)&n); if(check_create !=0){ printf("Thread creation failed"); exit(1); } check_create = pthread_create(&pthread2, NULL, sumpi2, (void *)&n); if(check_create !=0){ printf("Thread creation failed"); exit(1); } //等待第一個線程退出,並接收它的返回值(返回值存儲在thread1_return) check_end = pthread_join(pthread1, &thread1_return); if(check_end !=0 ){ printf("Thread end failed"); exit(1); } printf("%.20lf\n" ,*(double *)thread1_return); //cout << thread1_return << endl; ans += (*(double*)thread1_return); //等待第二個線程退出,並接收它的返回值(返回值存儲在thread2_return) check_end = pthread_join(pthread2, &thread2_return); if(check_end !=0 ){ printf("Thread end failed"); exit(1); } printf("%.20lf\n" ,*(double *)thread2_return); ans += (*(double*)thread2_return); printf("the pi is %.20lf\n" ,ans); return 0; } void * sumpi1(void * arg) { double n = *(double *)arg; ret1 = 0.0; for(int i = 0; i < n/2; i++) { double temp = (4 / (1 + ((i + 0.5)/n)*((i + 0.5)/n)))*(1.0/n); ret1 += temp; } //printf("%.20lf\n", ret1); //double * pret1 = &ret1; pthread_exit((void*)pret1); } void * sumpi2(void * arg) { double n = *(double *)arg; ret = 0.0; for(int i = n/2; i <= n; i++) { double temp = (4 / (1 + ((i + 0.5)/n)*((i + 0.5)/n)))*(1.0/n); ret += temp; } //double * pret = &ret; //printf("%.20lf\n", *pret); pthread_exit((void *)pret); }
