题目

链接


多进程

#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;
}
View Code

相关文章:

  • 2022-02-05
  • 2021-08-01
  • 2021-07-03
  • 2021-12-01
  • 2022-12-23
  • 2021-10-29
猜你喜欢
  • 2022-02-18
  • 2022-12-23
  • 2021-11-11
  • 2022-12-23
  • 2022-01-14
  • 2021-10-26
  • 2022-12-23
相关资源
相似解决方案