使用vfork进行多线程处理

时间:2013-10-09 18:33:58

标签: c++ multithreading parallel-processing fork pipe

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

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

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

这是我的代码,对于凌乱的代码和我的评论感到抱歉。这是我的测试代码,所以我搞得很乱。

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

`

1 个答案:

答案 0 :(得分:1)

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

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