C++ 语言 多线程的线程池设计实现

C++阿木 发布于 2025-06-14 7 次阅读


C++ 线程池设计实现

在多线程编程中,线程池是一种常用的设计模式,它可以有效地管理线程资源,提高程序的性能和响应速度。线程池通过预先创建一定数量的线程,并将任务分配给这些线程执行,从而避免了频繁创建和销毁线程的开销。本文将围绕C++语言,详细阐述线程池的设计与实现。

线程池的基本原理

线程池的基本原理如下:

1. 线程池初始化:在程序启动时,创建一定数量的线程,并将它们放入线程池中。
2. 任务队列:线程池中有一个任务队列,用于存放待执行的任务。
3. 线程执行:线程池中的线程从任务队列中取出任务并执行。
4. 线程回收:当线程执行完任务后,可以选择回收线程,或者让线程继续等待新的任务。

线程池的设计

1. 线程池类设计

线程池类需要具备以下功能:

- 初始化线程池,创建指定数量的线程。
- 提交任务到任务队列。
- 线程从任务队列中获取任务并执行。
- 线程池的关闭和回收。

以下是一个简单的线程池类设计:

cpp
include
include
include
include
include
include
include

class ThreadPool {
public:
ThreadPool(size_t threads) : stop(false) {
for (size_t i = 0; i < threads; ++i) {
workers.emplace_back([this] {
for (;;) {
std::function task;
{
std::unique_lock lock(this->queue_mutex);
this->condition.wait(lock, [this] { return this->stop || !this->tasks.empty(); });
if (this->stop && this->tasks.empty())
return;
task = std::move(this->tasks.front());
this->tasks.pop();
}
task();
}
});
}
}

template
auto enqueue(F&& f, Args&&... args)
-> std::future<#typename std::result_of::type> {
using return_type = typename std::result_of::type;

auto task = std::make_shared< std::packaged_task >(
std::bind(std::forward(f), std::forward(args)...)
);

std::future res = task->get_future();
{
std::unique_lock lock(queue_mutex);

if (stop)
throw std::runtime_error("enqueue on stopped ThreadPool");

tasks.emplace(

() { (task)(); });
}
condition.notify_one();
return res;
}

~ThreadPool() {
{
std::unique_lock lock(queue_mutex);
stop = true;
}
condition.notify_all();
for (std::thread &worker: workers)
worker.join();
}

private:
std::vector workers;
std::queue< std::function > tasks;

std::mutex queue_mutex;
std::condition_variable condition;
bool stop;
};

2. 任务队列设计

任务队列可以使用`std::queue`来实现,它是一个线程安全的队列,可以存储待执行的任务。

3. 线程设计

线程设计可以使用`std::thread`来实现,它提供了创建和管理线程的功能。

线程池的实现

以下是一个简单的线程池实现:

cpp
include
include
include
include
include
include
include
include

class ThreadPool {
public:
ThreadPool(size_t threads) : stop(false) {
for (size_t i = 0; i < threads; ++i) {
workers.emplace_back([this] {
for (;;) {
std::function task;
{
std::unique_lock lock(this->queue_mutex);
this->condition.wait(lock, [this] { return this->stop || !this->tasks.empty(); });
if (this->stop && this->tasks.empty())
return;
task = std::move(this->tasks.front());
this->tasks.pop();
}
task();
}
});
}
}

template
auto enqueue(F&& f, Args&&... args)
-> std::future<#typename std::result_of::type> {
using return_type = typename std::result_of::type;

auto task = std::make_shared< std::packaged_task >(
std::bind(std::forward(f), std::forward(args)...)
);

std::future res = task->get_future();
{
std::unique_lock lock(queue_mutex);

if (stop)
throw std::runtime_error("enqueue on stopped ThreadPool");

tasks.emplace(

() { (task)(); });
}
condition.notify_one();
return res;
}

~ThreadPool() {
{
std::unique_lock lock(queue_mutex);
stop = true;
}
condition.notify_all();
for (std::thread &worker: workers)
worker.join();
}

private:
std::vector workers;
std::queue< std::function > tasks;

std::mutex queue_mutex;
std::condition_variable condition;
bool stop;
};

int main() {
ThreadPool pool(4);

auto future = pool.enqueue([](int n) {
std::cout << "Hello from thread " << n << std::endl;
return n n;
}, 1);

std::cout << "Result: " << future.get() << std::endl;

return 0;
}

总结

本文详细介绍了C++语言中线程池的设计与实现。通过使用线程池,可以有效地管理线程资源,提高程序的性能和响应速度。在实际应用中,可以根据具体需求对线程池进行扩展和优化。