c++ - 如何使用多线程读取文件?

标签 c++ linux multithreading gcc

我的操作系统作业必须解决以下问题。我已经完成了一些工作,但我还没有完成。将不胜感激。

问题

您的任务是创建一个多线程文档分析器。你的程序应该能够使用 可变数量的线程来处理提供的文件,并产生一些关于它的统计信息。这 所需的数字是: • 单词数(通过计算空格数找到) • 字母的数量(通过使用 isalpha () 功能) • 标点字符的数量(通过使用 正点 () 功能)。 下面显示了一个涉及 4 个线程的示例运行: $ ./docAnal 4 测试.txt 字数:1245 字母 : 24313 标点符号:87 文档应该在所需的线程之间平均分配。你不应该硬编码你的 程序参数。它们应该从命令行读取,如上例所示

到目前为止,这是我的代码

#include <QThread>
#include <iostream>
#include <fstream>
#include <string>
#include <locale>
using namespace std;

//int count=0;
char  buff[200];
class MyThread: public QThread
{
    private : int space, word, punc = 0,countl=0;
    int ID;
public:
    MyThread(int i) : ID(i) {}
    void run (){ ifstream myfile;
        ifstream fin;
        fin.open("example.txt");
        myfile.open("example.txt");
        cout<<"Reading file"<<endl;
        //cout<<"words ="<<word;

        while(!myfile.eof())
        {

            myfile>>buff;
            word++;
            countl=countl+strlen(buff);
        }

        for (int i=0;i<strlen(buff);i++)
        {
            if (ispunct(buff[i])) punc++;
        }

        cout<<"words ="<<word-1<<endl;
        cout<<"Letter="<<countl-(4+punc)<<endl;
        cout<<"Puncuation ="<<punc<<endl;
    }
};

int  main()
{

    MyThread *counter [1];
    for (int i = 0;i<1;i++){
        counter[i] = new MyThread(i);
        counter[i]->start();
    }

    for (int i = 0;i<1;i++){
        counter[i]->wait();
    }
    return 0;
}

我只能使用一个线程获得输出。我不知道如何将它分成几部分并让 4 个线程连续读取它。请指出正确的方向。

最佳答案

您可以获得文件的长度并将该数字除以线程数。

然后,寻找每个可能的开始位置(使用 seekg())并通过读取到下一个空间(std::isspace())来调整它以避免将单词切成两半。

然后将每个开始位置和结束位置传递给一个线程(结束位置是后面分区的开始位置)。

然后每个线程使用 seekg() 移动到其分配的位置,并使用 tellg() 确定何时到达分配的终点。

关于c++ - 如何使用多线程读取文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26762575/

相关文章:

c++ - 如何获得 Sigma NcR mod 1000000007

c++ - i =++i 和++i 的区别

Java套接字 - 客户端不从服务器的套接字读取字符串

python - 使用多个管道从 Python 执行 Shell 脚本

c++ - 如何修复 g++ 内存范围重叠?

java - 当前线程调用多个方法

c# - 通过smtp服务器异步发送电子邮件-多线程发送电子邮件

c++ - 是否可以针对使用的类设置重载 operator+ 的优先级?

c++ - 如何从 OpenCV FileNode 映射中检索键值对?

c - 如何让套接字服务器只接受一次