c++ - 条件线程制作

标签 c++ c multithreading pthreads

这个问题是我自己解决的!

我正在读取一个 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/

相关文章:

C# 在多个线程上拆分循环

c - linux定时器是进程吗

c# - 如何编码从 C 头文件中的宏定义的结构?

c++ - shared_ptr 不报告引用对象删除

c++ - 这是编译器错误还是我的代码?

我们可以使用暴力通过指向数组的指针更改数组的基地址吗?

c - 将 tcmalloc 与 glib 结合使用

c - 指向特定固定地址的指针

c++ - 如何获取 ConnectEx() 指针

java - volatile 会保护我免受所有幕后多线程危害吗?