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++ - VirtualProtect 和 kernel32.dll - 尝试访问无效地址

c++ - 使用 boost::asio 和 c++11 lambda 的简单回调控制

c - Ubuntu/Xfce 禁用特定应用程序的全局快捷方式

c - 如何在Windows XP操作系统上使用OpenCL?

c# - 有什么方法可以捕获任何生成的线程中的异常吗?

java - 任意时刻有多少个线程可以访问该 Java 对象的同步代码?

c++ - `make_unique` 相对于普通构造函数的优势?

c++ - 具有模板化参数的函数指针歧义

找不到最常用的词

php - 用PHP编写线程安全的文件