【问题标题】:Multithreaded MD5 Hashing多线程 MD5 哈希
【发布时间】: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


【解决方案1】:

您在这里看到的是所有线程都在读取同一个文件并执行相同的工作。这导致该文件必须被读取num_threads 次,可能会导致大约num_threads 的减速(因为文件 I/O 可能在关键路径上),或者由于更多的缓存未命中可能甚至更多。

您可以尝试将整个文件读入内存,在线程之间拆分,然后让每个线程处理该文件内容的子集。

【讨论】:

    猜你喜欢
    • 2012-08-17
    • 1970-01-01
    • 1970-01-01
    • 2020-12-08
    • 1970-01-01
    • 1970-01-01
    • 2014-05-19
    • 2012-05-28
    相关资源
    最近更新 更多