【发布时间】:2018-02-01 05:12:54
【问题描述】:
我正在尝试对一个程序进行多线程处理,该程序从文件中获取单词然后散列这些并写入另一个。
如果我在不使用多线程的情况下制作它,它会非常快,它只能使用 15-20% 的 CPU,并且速度大约为 300.000line/s
但是当我尝试使用多线程时,它只会变慢并开始以 17000 行/秒的速度散列,你能帮帮我吗?
谢谢
#include <iostream> // std::cout, std::streambuf, std::streamsize
#include <fstream> // std::ifstream
#include <string>
#include <thread>
#include "md5.h"
using namespace std;
static const int num_threads = 10;
void call_from_thread(int tid) {
cout << "Launched by thread " << tid << std::endl;
int cl = 0;
int uscita = 0;
int parole = 0;
char* contents;
ifstream istr("test.txt");
if (istr) {
streambuf * pbuf = istr.rdbuf();
streamsize size = pbuf->pubseekoff(0, istr.end);
pbuf->pubseekoff(0, istr.beg); // rewind
contents = new char[size];
pbuf->sgetn(contents, size);
istr.close();
ofstream myfile;
myfile.open("out.txt");
do {
string prova("");
uscita = 0;
do {
if (contents[cl] == '\n') {
uscita = 1;
}
prova += contents[cl];
cl += 1;
} while (uscita != 1);
parole += 1;
//cout << prova << ":" << md5(prova) << endl;
myfile << prova << ":" << md5(prova) << endl;
} while (parole != 9586054);
myfile.close();
}
}
int main()
{
thread t[num_threads];
//Launch a group of threads
for (int i = 0; i < num_threads; ++i) {
t[i] = thread(call_from_thread, i);
}
cout << "Launched from the main\n";
//Join the threads with the main thread
for (int i = 0; i < num_threads; ++i) {
t[i].join();
}
return 0;
}
【问题讨论】:
-
你需要多少个cpu核心才能运行它?...
-
你有十个线程都从同一个文件中读取和查找。如果您不使用 SSD,那么物理磁盘头必须随着每个线程上下文切换来回移动。尝试先将完整文件读入内存,然后使用线程从内存缓冲区中执行所需的操作。
-
@Joe 我在 48 核服务器上运行它
-
@Someprogrammerdude 我正在使用固态硬盘
-
另外,为什么每个线程都在读取处理整个文件?如果线程都对相同的数据执行相同的工作,那么线程的目的是什么?此外,每个线程还写入相同的输出文件,覆盖彼此的数据。
标签: c++ multithreading hash md5