C语言问题求解,利用C语言求解

实验内容3. 进阶进程创建与控制
求数组长度为10000的浮点数(精确小数点右4位)计算值。
要求:
1.对于长度为10000的数组,随机生成10000个浮点数(父进程);
2.创建4个子进程,分别求2500个浮点数之和;
3.父进程完成10000个浮点数之和,并打印结果;
4.统计顺序计算的时间和多个进程采用多道程序设计完成计算的时间。

大家看看这个要怎么用C语言实现


#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/time.h>

#define ARRAY_SIZE 10000
#define CHILD_COUNT 4
#define CHILD_ARRAY_SIZE (ARRAY_SIZE / CHILD_COUNT)

double array[ARRAY_SIZE];

double calculate_sum(int start, int end) {
    double sum = 0;
    for (int i = start; i < end; i++) {
        sum += array[i];
    }
    return sum;
}

int main() {
    // Generate random numbers
    for (int i = 0; i < ARRAY_SIZE; i++) {
        array[i] = (double)rand() / RAND_MAX;
    }

    // Sequential calculation
    struct timeval start_time, end_time;
    gettimeofday(&start_time, NULL);

    double sum = calculate_sum(0, ARRAY_SIZE);

    gettimeofday(&end_time, NULL);
    double seq_time = (end_time.tv_sec - start_time.tv_sec) + (end_time.tv_usec - start_time.tv_usec) / 1000000.0;

    printf("Sequential sum: %.4lf\n", sum);

    // Parallel calculation
    gettimeofday(&start_time, NULL);

    int pipefd[CHILD_COUNT][2];
    for (int i = 0; i < CHILD_COUNT; i++) {
        if (pipe(pipefd[i]) == -1) {
            perror("pipe");
            exit(EXIT_FAILURE);
        }
        pid_t pid = fork();
        if (pid == -1) {
            perror("fork");
            exit(EXIT_FAILURE);
        } else if (pid == 0) { // Child process
            close(pipefd[i][0]); // Close unused read end of pipe
            double sum = calculate_sum(i * CHILD_ARRAY_SIZE, (i + 1) * CHILD_ARRAY_SIZE);
            write(pipefd[i][1], &sum, sizeof(sum)); // Write sum to pipe
            close(pipefd[i][1]); // Close write end of pipe
            exit(EXIT_SUCCESS);
        } else { // Parent process
            close(pipefd[i][1]); // Close unused write end of pipe
        }
    }

    sum = 0;
    for (int i = 0; i < CHILD_COUNT; i++) {
        double child_sum;
        read(pipefd[i][0], &child_sum, sizeof(child_sum)); // Read sum from pipe
        sum += child_sum;
        close(pipefd[i][0]); // Close read end of pipe
    }

    gettimeofday(&end_time, NULL);
    double par_time = (end_time.tv_sec - start_time.tv_sec) + (end_time.tv_usec - start_time.tv_usec) / 1000000.0;

    printf("Parallel sum: %.4lf\n", sum);

    printf("Sequential time: %.6lf s\n", seq_time);
    printf("Parallel time: %.6lf s\n", par_time);

    return 0;
}

上述代码使用rand()函数生成10000个随机浮点数,并将它们存储在array数组中。然后,使用calculate_sum()函数计算数组的总和,该函数接受起始索引和结束索引作为参数。父进程首先计算整个数组的总和,然后使用fork()函数创建4个子进程,每个子进程都计算一个子数组的总和。每个子进程使用一个管道将其计算的总和写回父进程。最后,父进程从每个子进程的管道中读取它们的计算结果,并将所有子进程的总和相加以得到整个数组的总和。

不知道你这个问题是否已经解决, 如果还没有解决的话:

如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^