首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >多进程IO比多线程IO快

多进程IO比多线程IO快
EN

Stack Overflow用户
提问于 2013-12-14 15:42:36
回答 1查看 120关注 0票数 0

我有一个测试程序,它根据命令行选项执行以下操作:

1)分叉多个进程,每个进程按顺序读取相同的文本文件

2)创建多个线程,每个线程依次读取相同的文本文件。

我已经注意到,多线程方法比多进程方法多花费35 %的时间。

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

机器配置: 8GB内存,4核,

下面是代码和测试结果:

代码语言:javascript
复制
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。

实际用户1m40.149ssys 0m3.360

多线程所需时间:

时间。/io_t 20

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

EN

回答 1

Stack Overflow用户

发布于 2013-12-14 15:49:32

我怀疑您是在一些带有默认内核IO设置的现代桌面Linux发行版上测试的--这就是我怀疑找到答案的地方。

  • 不同的进程有不同的IO上下文,因此每个上下文的IO都是严格顺序的。
  • 不同的线程共享父进程的IO上下文,因此如果不同的线程取得了不同的进展(这在4个内核和20个线程中是不可避免的),则IO通过从不同位置的顺序读取随机化。
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/20585132

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档