gpt4 book ai didi

c++ - 多线程不改变速度

转载 作者:搜寻专家 更新时间:2023-10-31 02:22:32 24 4
gpt4 key购买 nike

我目前正在致力于加速我的一个 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 解析器也很有可能进行大量内存分配,如果许多线程同时分配内存,内存分配速度可能会减慢。

关于c++ - 多线程不改变速度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30197017/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com