在 C++03 中,我将 pthread 与一个自建线程池一起使用,该线程池始终保持几个线程运行(因为 pthread_create
很慢),这样我就可以启动小线程任务而不考虑性能问题。
现在,在 C++11 中,我们有了 std::thread
。我想标准没有说明具体的实现,所以我的问题是关于标准库的实现。他们通常会选择一种池化方法,其中构造 std::thread
s 很便宜(例如,不会在 posix 上调用 pthread_create
),还是会 std: :thread
只是一个包装器?
换句话说,C++11 中是否仍然推荐使用线程池,还是应该在需要时创建一个 std::thread
并将性能留给标准库?
最佳答案
通常,std::thread
应该是底层系统原语的最小包装。例如,如果你在 pthread
平台上,你可以用下面的程序测试,无论你创建多少线程,它们都是用唯一的 pthread_t
ids 创建的(这意味着它们是动态创建的,而不是从线程池中借来的):
#include <assert.h>
#include <mutex>
#include <set>
#include <thread>
#include <vector>
#include <pthread.h>
int main() {
std::vector<std::thread> workers;
std::set<long long> thread_ids;
std::mutex m;
const int n = 1024;
for (int i = 0; i < n; ++i) {
workers.push_back(std::thread([&] {
std::lock_guard<std::mutex> lock(m);
thread_ids.insert(pthread_self());
}));
}
for (auto& worker : workers) {
worker.join();
}
assert(thread_ids.size() == n);
return 0;
}
所以线程池仍然很有意义。也就是说,我看过一个视频,其中 C++ 委员会成员讨论了关于 std::async
(IIRC) 的线程池,但我现在找不到。
关于C++ 11:std::thread池化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12993451/