支持"连接绑定线程"的线程池
More...
#include <thread_pool.hpp>
|
| | ThreadPool (size_t threads) |
| | 构造线程池
|
| |
| | ~ThreadPool () |
| | 析构线程池
|
| |
| void | enqueue_to (size_t thread_index, std::function< void()> task) |
| | 提交任务到指定线程
|
| |
| template<class F , class... Args> |
| auto | enqueue (F &&f, Args &&... args) -> std::future< std::invoke_result_t< F, Args... > > |
| | 提交任务到任意空闲线程
|
| |
| size_t | get_thread_count () const |
| | 获取线程池中的线程数量
|
| |
支持"连接绑定线程"的线程池
每个工作线程有独立的任务队列,可以指定任务在哪个线程执行。 这样同一个连接的所有操作都在同一个线程中串行执行,避免锁竞争。
- 设计特点
- 每个线程独立的无锁任务队列(moodycamel::BlockingConcurrentQueue)
- 支持指定线程执行任务(enqueue_to)
- 支持轮询分配任务(enqueue)
- 优雅关闭:发送空任务通知线程退出
- 使用示例
pool.enqueue_to(connection_fd % pool.get_thread_count(), [&]() {
handle_connection(connection_fd);
});
auto future = pool.enqueue([]() { return compute_result(); });
支持"连接绑定线程"的线程池
Definition thread_pool.hpp:48
◆ ThreadPool()
| fix40::ThreadPool::ThreadPool |
( |
size_t |
threads | ) |
|
|
inlineexplicit |
构造线程池
- Parameters
-
创建指定数量的工作线程,每个线程有独立的任务队列。
◆ ~ThreadPool()
| fix40::ThreadPool::~ThreadPool |
( |
| ) |
|
|
inline |
析构线程池
向每个线程发送空任务以通知退出,然后等待所有线程结束。
◆ enqueue()
template<class F , class... Args>
| auto fix40::ThreadPool::enqueue |
( |
F && |
f, |
|
|
Args &&... |
args |
|
) |
| -> std::future<std::invoke_result_t<F, Args...>> |
提交任务到任意空闲线程
- Template Parameters
-
- Parameters
-
- Returns
- std::future 用于获取任务返回值
使用轮询方式分配任务到各线程,实现简单的负载均衡。
- Exceptions
-
| std::runtime_error | 如果线程池已停止 |
◆ enqueue_to()
| void fix40::ThreadPool::enqueue_to |
( |
size_t |
thread_index, |
|
|
std::function< void()> |
task |
|
) |
| |
|
inline |
提交任务到指定线程
- Parameters
-
| thread_index | 目标线程索引(会自动取模) |
| task | 要执行的任务 |
用于连接绑定场景,确保同一连接的所有操作在同一线程串行执行。
- Note
- 如果 thread_index >= thread_count_,会自动取模
-
线程池停止后调用此方法无效
◆ get_thread_count()
| size_t fix40::ThreadPool::get_thread_count |
( |
| ) |
const |
|
inline |
获取线程池中的线程数量
- Returns
- size_t 线程数量
The documentation for this class was generated from the following file: