多线程不会改变速度



我目前正在努力加速我的C 程序之一,并试图发现美丽的多线程世界。

std::vector<std::thread> threadPool;
threadPool.clear();
for(int t = 0; t < nbThreads; ++t){
    threadPool.push_back(std::thread(myFunction, std::ref(rep), std::ref(branch1));
}
for(auto t = threadPool.begin(); t < threadPool.end() ; ++t){
    t->join();
}

我不明白的是,无论我使用的线程数量,速度都不会改变!(约30秒)。

总结:如果我的代码错了,怎么了?如果没有错,在什么情况下,我应该使用多线程来加快计算?

编辑:我在i7-4810mq机器上运行

编辑2:这是MyFunction所做的(解析XML文件)

void myfunction(DIR*& rep, struct dirent*& branch1){
mtx.lock();
while ((branch1 = readdir(rep)) != NULL){
    mtx.unlock()
    TiXmlDocument doc(branch1->d_name);
    if(doc.LoadFile()){
            //parse file
    }
    mtx.lock();
}
mtx.unlock();
}

很有可能您的代码受到文件I/O的限制。您的XML解析器也很有可能进行大量内存分配,并且如果许多线程同时分配内存,则内存分配可能会放慢速度。

最新更新