每次 std::thread 要分配栈、创建内核对象,开销约数百微秒。频繁创建销毁远不如复用线程。
class ThreadPool {
std::vector workers;
std::queue> tasks;
std::mutex mtx;
std::condition_variable cv;
bool stop = false;
public:
ThreadPool(int n) {
for (int i = 0; i < n; i++) {
workers.emplace_back([this] {
while (true) {
std::function task;
{
std::unique_lock lock(mtx);
cv.wait(lock, [this]{ return stop || !tasks.empty(); });
if (stop && tasks.empty()) return;
task = std::move(tasks.front());
tasks.pop();
}
task();
}
});
}
}
template
auto enqueue(F&& f, Args&&... args)
-> std::future {
using R = decltype(f(args...));
auto task = std::make_shared>(
std::bind(std::forward(f), std::forward(args)...));
std::future res = task->get_future();
{
std::unique_lock lock(mtx);
tasks.emplace([task]{ (*task)(); });
}
cv.notify_one();
return res;
}
};
ThreadPool pool(4);
auto f = pool.enqueue([](int x) { return x * x; }, 42);
std::cout << f.get(); // 1764