首页 > 解决方案 > 主线程比其他线程慢

问题描述

我有一个 C++ 中的多线程程序。我想知道为什么如果主线程执行部分计算,那么(在我的测试中)主线程总是比其他线程慢几秒钟。(为了比较其他线程在 9 秒内运行,主线程在 11 秒内运行)。

如果我不使用主线程进行部分计算,那么所有线程大约会同时完成。IE :

int numThreads = 4;
std::thread *threads = new std::thread[numThreads];

for (int i = 0; i < numThreads; i++){
   threads[i] = std::thread(func)
}

for (int i = 0; i < numThreads; i++){
    threads[i].join();
}

对比

int numThreads = 4;
std::thread *threads = new std::thread[numThreads - 1];

for (int i = 0; i < numThreads-1; i++){
   threads[i] = std::thread(func);
}

func();

for (int i = 0; i < numThreads-1; i++){
   threads[i].join();
}

非常感谢!

标签: multithreadingc++11

解决方案


推荐阅读