这个问题是我自己解决的!
我正在读取一个 C
文件,其中每一行都包含一个数字(0 到 1000000 之间的随机数):
1121
84
928434
9999
70373
...
我逐行读取,对于每一行,我都会进行一些计算并将大量数据写入名为 d_file.txt
的文件中,其中 d
是列出读取数的有效数字。假设写入文件需要很长时间,所以我想在多线程中编写代码,这样我就可以同时写入多个文件(~10)。虽然单线程
C
代码很明显,但我想知道使用pthread
的多线程
代码是什么样子.
单线程
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;
}
最佳答案
您绝对可以同时读取一个文件以及文件的多个部分。查看this所以回答。如果这对您来说还不够,那么还有更多关于 SO 和网络的内容解释如何并行读取和写入 ASCII。
关于c++ - 条件线程制作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38112956/