设计一个线程池涉及到多个方面,包括线程的创建与销毁、任务的提交与执行、线程间的通信等。
以下不念给出的是一个简单的线程池设计思路:
给个例子:
#include
#include
#include
#include
#include
#include
#include
class ThreadPool {
public:
ThreadPool(size_t numThreads) : stop(false) {
for (size_t i = 0; i < numThreads; ++i) {
workers.emplace_back([this] {
while (true) {
std::function task;
{
std::unique_lock lock(queueMutex);
condition.wait(lock, [this] { return stop || !tasks.empty(); });
if (stop && tasks.empty()) {
return;
}
task = std::move(tasks.front());
tasks.pop();
}
task();
}
});
}
}
~ThreadPool() {
{
std::unique_lock lock(queueMutex);
stop = true;
}
condition.notify_all();
for (std::thread &worker : workers) {
worker.join();
}
}
template
void enqueue(F&& f) {
{
std::unique_lock lock(queueMutex);
tasks.emplace(std::forward(f));
}
condition.notify_one();
}
private:
std::vector workers;
std::queue tasks;
std::mutex queueMutex;
std::condition_variable condition;
bool stop;
};
int main() {
ThreadPool pool(4);
for (int i = 0; i < 8; ++i) {
pool.enqueue([i] {
std::cout