0

我有一个基于命令行选项执行以下操作的测试程序:

1)fork多个进程,每个进程完全顺序读取同一个文本文件

2)创建多个线程,每个线程完全顺序读取同一个文本文件

我注意到多线程方法比多进程方法多花费大约 35% 的时间。

为什么多进程 IO 比多线程 IO 快?

机器配置:8GB RAM,4 核,

下面是代码和测试结果:

using namespace std;
#include<fstream>
#include<iostream>
#include<pthread.h>
#include<errno.h>
#include<sys/wait.h>
#include <string>



void* run_thread(void * tmp)
{
    int counter=0;
    string s;
    string input_file("perf_input");
    ifstream in(input_file.c_str(), ios_base::in);
    while(getline(in, s))
    {
        counter++;
    }
    cout<<"counter "<<counter<<endl;
}

int main(int argc, char *argv[])
{
    if(argc != 3)
    {
        cout<<"Invalid number of arguments "<<endl;
        return -1;
    }


    if(argv[1][0] == 'p')
    {
        cout<<"fork process"<<endl;
        int n = atoi(argv[2]);
        cout<<" n " <<n<<endl;

        for(int i=0;i<n;i++)
        {
            int cpid = fork();

            if(cpid< 0)
            {
                cout<<"Fork failed "<<endl;
                exit(0);
            }
            else if(cpid == 0)
            {
                //child
                cout<<"Child created "<<endl;
                run_thread(NULL);
                cout<<"Child exiting "<<endl;
                exit(0);
            }
        }

        while (waitpid(-1, NULL, 0))
        {
            if (errno == ECHILD)
            {
                break;
            }
        }
    }
    else
    {
        cout<<"create thread"<<endl;
        int n = atoi(argv[2]);
        cout<<" n " <<n<<endl;

        pthread_t *tids = new pthread_t[n];
        for(int i=0;i <n; i++)
        {
            pthread_create(tids + i, NULL, run_thread, NULL);
        }

        for(int i=0;i <n; i++)
        {
            pthread_join(*(tids + i), NULL);
        }
    }
}

多进程花费的时间:

时间 ./io_test p 20

真实 0m26.170s 用户 1m40.149s 系统 0m3.360s

多线程耗时:

时间 ./io_test t 20

真实 0m35.561s 用户 2m14.245s 系统 0m4.577s

4

1 回答 1

0

我怀疑您使用默认内核 IO 设置在一些现代桌面 Linux 发行版上对此进行了测试——这就是我怀疑可以找到答案的地方。

  • 不同的进程有不同的IO上下文,所以每个上下文的IO都是严格顺序的
  • 不同的线程共享其父进程的 IO 上下文,因此如果不同的线程进行不同的进度(这在 4 核和 20 线程的情况下是不可避免的),则通过从不同位置交错顺序读取来随机化 IO
于 2013-12-14T15:49:32.890 回答