条件制线

Conditional Thread Making

本文关键字:条件      更新时间:2023-10-16

这道题是我自己做的!

我正在阅读一个文件,在C中,其中每行包含一个数字(随机在0到1000000之间):

1121
84
928434
9999
70373
...

我逐行读取,对于每一行,我做一些计算并将大量数据写入名为d_file.txt的文件中,其中d是读取数的列表有效数字。假设写入文件需要很长时间,所以我想在multi-thread中编写代码,这样我就可以同时写入多个文件(~10)。虽然single thread C代码是显而易见的,但我想知道multi-thread代码使用pthread看起来像什么。

single-thread C代码:

#include <fstream>
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int func(int a)
{
        //assume the data is big and writing takes a long time
        int data = a;
        return data;
}
int main()
{
        ifstream in("numbers.txt");
        int a;
        while(in >> a)
        {
                stringstream ss;
                ss << a%10;
                string str;
                ss >> str;
                str += "_File.txt";
                ofstream out(str.c_str(), fstream::in | fstream::out | fstream::trunc);
                //This is blocking, if write takes long
                //but can be rewritten in a multi-thread fashion
                // to allow upto 10 simultaneous file write
                out << func(a) << endl;
        }
        return 0;
}

您绝对可以同时读取一个文件和文件的多个部分。看看这个答案吧。如果这对你来说还不够,还有很多关于SO和整个网络解释如何并行地读取和写入ASCII。