条件制线
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。
相关文章:
- 为什么"do while"循环不断退出,即使条件计算结果为 false?
- 在没有太多条件句的情况下,我如何避免被零除
- 基于多个条件处理地图中的所有元素
- 条件constexpr函数
- 无论条件是否为true,if总是在c++中执行
- 我可以使用条件运算符初始化C风格的字符串文字吗
- 基于模板值的条件变量
- 多个If语句与使用逻辑运算符计算条件的单个语句的比较
- 将按位if条件转换为普通if条件
- 条件断点在不应该触发时触发
- 为什么简单的算术减法在"if"条件下不起作用?
- 如何在for循环中包含两个索引值的测试条件
- 如果条件为TRUE(最佳方式?),则在do while循环中后置增量
- 我提出什么条件才能再加5%的折扣
- 循环中的条件:为什么每次都调用strlen(),而vector.size()只调用一次
- 即使没有满足他们的条件,我也无法通过一些 do-while 循环
- 如何编写一个使用n倍三元条件语句的C++布尔函数
- 没有超时的C++条件变量
- 正在LLVM中检测整数比较条件
- 在条件变量中触发错误信号的频率是多少