我必须为我的操作系统作业解决以下问题。我做了一些工作,但我还没有完成。帮助将不胜感激。如何使用多线程读取文件?
问题
你的任务是创建一个多线程的文档分析器。您的程序应该能够使用可变数量的线程来处理提供的文件,并生成一些关于它的统计信息。该 所需的数字是: • 字数 • 字母 数量(通过使用 因而isalpha ()函数中)• 的标点字符(数字(以计数的空格数中)通过使用 ispunct ()函数)找到。 一个例子的运行将涉及4个线程如下所示: $ ./docAnal 4的test.txt 单词:1245 信件:24313 标点:87 文件应所需threads.You之间应平分不要硬编码您的 程序参数。他们应该在命令行被解读为在上面的示例所示
这是到目前为止我的代码
#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个线程连续读取。请指向正确的方向。
可能打开该文件中的每个线程读取文件(除以线程数)的不同部分,并计算上有什么阅读统计线程。然后结合所有线程的结果。 – drescherjm 2014-11-05 16:52:35
我会使用mmap()映射文件一次,然后启动线程并使它们从特定位置(文件中的0%,25%,50%和75%)读取。 – 2014-11-05 16:53:36