c++ - 使用 vfork 的多线程

标签 c++ multithreading parallel-processing fork pipe

我的代码有问题,这是我第一次使用 fork。一旦我使用管道或 vfork,我的子处理器就会继续串行而不是并行。我得到了我预期的答案,但程序没有按照我的要求进行。

我的基本程序只是计算 1 到 100000000、1+2+3+4...10000 等的总和。

我只是想学习 fork 和管道并对它们进行基准测试。

这是我的代码,对于乱七八糟的代码和我的评论深表歉意。这是我的测试代码,所以我弄得一团糟。

#include <iostream>
#include <ctime>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <errno.h>
#include <stdlib.h>
#include <stdio.h>
#include <csignal>
#include <cstdlib>
#include <fstream>
#include <fcntl.h>
#include <string.h>

using namespace std;

int main () {

    long sumTemp =0;
    long sum = 0;
    long times = 1000000000; // number to add up
    int threads = 4;
    long amount[threads];
    pid_t childPids[threads];
    pid_t p;
    time_t tstart, tend;
    long lastNumber=0;
    long addedValue =0;
    int fd[2];
    long readbuffer = 0;
    int number = 0;

// Counting time

    tstart = time(0);

    for (int p=0; p<=threads; p++){
            amount[p]=0;
    }

//Having the task divided to threads

    long divided = (times/threads);
    for (int j=1; j<=threads; j++){
            addedValue += divided;
            amount[j]= addedValue;
            cout << amount[j-1] << " .... " << j << " ... " << amount[j] << endl;

    }

    // Child making

    for (int j=0; j<threads; j++){

            // running fork
            pipe(fd);
            p = vfork();

            if (p== -1)
            {
                    printf("Error occoured with fork()\n");
                    exit(99);                       // exit status 99
            }

            else if (p == 0){

                    //calculation

                    cout << " child : " << j << " " << p <<endl;

                    for (long i=(amount[j]+1); i<=amount[j+1]; i++){
                            sumTemp += i;

                    }

                    exit(0);
            }
            else {

                    childPids[j] = p;
                    sum = sumTemp;

            }

    }

    for(int k = 0; k < threads; k++){
    waitpid(childPids[k], NULL, WNOHANG);
    }

    tend = time(0);
    cout << endl << " Sum of adding " << times << "." << endl;
    cout << " Sum : " << sum << endl;
    cout << " It took " << difftime(tend, tstart) << " second(s)."
    << endl << endl;
}

`

最佳答案

使用 fork(),而不是 vfork()vfork() 仅应在子进程将在启动后不久调用 exec() 时使用。 vfork() 暂停父进程,直到子进程退出或调用 exec()

What is the difference between fork() and vfork()?

关于c++ - 使用 vfork 的多线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19279922/

相关文章:

random - 随机数种子的可能来源

algorithm - 无死锁与无饥饿

c++ - 全高清 2D 纹理内存 OpenGL

c++ - 在 C++ 中捕获 MySQL 错误

c++ - boost::asio 中 async_read() 中的 EOF

c++ - 从文件读取 diskpart 错误

java - 线程优先级无法正常工作。我的代码中做错了什么?

2 个线程的 Java 扫描器

c - 为什么 pthread 条件变量不起作用

c++ - OpenMP 中单个指令和部分指令之间的区别