C / C++ / 系统课时
用线程池分摊新连接负载
用线程池分摊新连接负载
本节在 one loop per thread 之上增加 EventLoopThreadPool:监听线程只执行 accept 和轻量连接初始化,然后按轮询策略把新连接交给多个 I/O Loop。这样既能利用多核并行处理连接,又不需要为每个连接单独创建线程。
学习目标
- 实现由多个
EventLoopThread组成的 I/O 线程池。 - 使用轮询策略把新连接稳定分配到不同
EventLoop。 - 明确 Acceptor、主 Loop 与子 Loop 之间的职责边界。
新连接应该去哪里
多 Reactor 模型中,监听 socket 通常仍绑定在主 EventLoop。主线程收到监听 fd 的可读事件后执行 accept,为新连接选择一个子 Loop;连接后续的读写事件则注册到该子 Loop,不再长期占用监听线程。

这种拆分让监听线程可以迅速回到下一次 accept,同时让不同连接在多个 CPU 核心上并行执行事件回调。线程数量并非越多越好,实际项目应结合 CPU 核数、回调耗时和上下文切换成本压测决定。
实现 EventLoopThreadPool
下面给出一个可运行的最小实现。EventLoop 只模拟线程常驻,EventLoopThreadPool 负责启动三个工作 Loop,并通过 next_ 维护下一次轮询位置。
#include <condition_variable>
#include <iostream>
#include <memory>
#include <mutex>
#include <thread>
#include <vector>
class EventLoop {
public:
explicit EventLoop(int index) : index_(index) {}
int index() const {
return index_;
}
void loop() {
std::unique_lock<std::mutex> lock(mutex_);
cv_.wait(lock, [this] { return quit_; });
}
void quit() {
{
std::lock_guard<std::mutex> lock(mutex_);
quit_ = true;
}
cv_.notify_one();
}
private:
int index_;
std::mutex mutex_;
std::condition_variable cv_;
bool quit_ = false;
};
class EventLoopThread {
public:
explicit EventLoopThread(int index) : index_(index) {}
~EventLoopThread() {
if (!thread_.joinable()) {
return;
}
// loop_ 的读取与工作线程中的清空操作必须同步。
{
std::lock_guard<std::mutex> lock(mutex_);
if (loop_ != nullptr) {
loop_->quit();
}
}
thread_.join();
}
EventLoop* startLoop() {
thread_ = std::thread([this] { threadFunc(); });
std::unique_lock<std::mutex> lock(mutex_);
cv_.wait(lock, [this] { return loop_ != nullptr; });
return loop_;
}
private:
void threadFunc() {
EventLoop loop(index_);
{
std::lock_guard<std::mutex> lock(mutex_);
loop_ = &loop;
}
cv_.notify_one();
loop.loop();
{
std::lock_guard<std::mutex> lock(mutex_);
loop_ = nullptr;
}
}
int index_;
std::thread thread_;
std::mutex mutex_;
std::condition_variable cv_;
EventLoop* loop_ = nullptr;
};
class EventLoopThreadPool {
public:
explicit EventLoopThreadPool(int threadCount)
: threadCount_(threadCount) {}
void start() {
for (int i = 0; i < threadCount_; ++i) {
auto thread = std::make_unique<EventLoopThread>(i);
loops_.push_back(thread->startLoop());
threads_.push_back(std::move(thread));
}
}
EventLoop* getNextLoop() {
if (loops_.empty()) {
return nullptr;
}
// 监听线程串行调用时,普通下标即可完成无锁轮询。
EventLoop* loop = loops_[next_];
next_ = (next_ + 1) % loops_.size();
return loop;
}
private:
int threadCount_;
std::size_t next_ = 0;
std::vector<std::unique_ptr<EventLoopThread>> threads_;
std::vector<EventLoop*> loops_;
};
int main() {
EventLoopThreadPool pool(3);
pool.start();
for (int connectionId = 101; connectionId <= 106; ++connectionId) {
EventLoop* ioLoop = pool.getNextLoop();
std::cout << "connection " << connectionId
<< " -> loop " << ioLoop->index() << '\n';
}
}预期输出
connection 101 -> loop 0
connection 102 -> loop 1
connection 103 -> loop 2
connection 104 -> loop 0
connection 105 -> loop 1
connection 106 -> loop 2轮询只决定新连接最初归属哪个 Loop,并不会在后续请求中不断迁移连接。连接 101 被分给 Loop 0 后,它的 channel 注册、读写回调和关闭流程都应尽量保持在 Loop 0 所在线程,避免多个线程同时修改同一个连接状态。
接入真实 accept 流程
真实网络库中,Acceptor 得到新 fd 后通常先选择目标 Loop,再构造 TcpConnection。如果 channel 注册必须发生在目标 I/O 线程,就应通过 runInLoop() 或 queueInLoop() 投递,而不是从监听线程直接操作子 Loop 内部状态。
片段示例,依赖网络库已经提供 getNextLoop()、TcpConnection 和 runInLoop():
EventLoop* ioLoop = threadPool_.getNextLoop();
auto conn = std::make_shared<TcpConnection>(ioLoop, connfd);
ioLoop->runInLoop([conn] {
conn->connectEstablished();
});生效行为是监听线程完成连接选择后迅速返回处理下一次 accept,而 connectEstablished() 在目标 I/O 线程执行,并由该 Loop 注册连接对应的读写事件。验证时可以在回调中记录 Loop 编号,确认同一连接后续事件始终落在同一个编号上。
轮询策略的边界
轮询的优点是实现简单、分配稳定,而且当 getNextLoop() 只由监听线程调用时不需要额外加锁。但它均衡的是连接数量,不是实际 CPU 或网络负载。若少量长连接承担大量消息,即使三个 Loop 的连接数接近,负载仍可能明显倾斜。
线程池的职责也应保持克制:管理 I/O 线程生命周期、保存可用 Loop、为新连接选择目标 Loop。协议解析、业务计算和耗时任务不应塞进这个线程池。这样主 Reactor 专注连接接入,子 Reactor 专注连接 I/O,后续即使再引入业务线程池,三类并发职责也能保持清晰。