代码拉取完成,页面将自动刷新
// mini_reactor.cpp —— 手写一个 epoll 事件循环 echo 服务器,并量化"回调阻塞"的代价
//
// 编译:g++ -std=c++17 -O2 -pthread mini_reactor.cpp -o mini_reactor
//
// 用法:./mini_reactor <并发连接数> <每连接请求数> [slow|pool]
// 默认 A:handler 很轻(纯 echo)—— 事件循环的理想用法
// slow B:handler 里做一次 5ms 阻塞调用 —— 事件循环被整个卡住(反例)
// pool C:阻塞调用交给线程池,用 eventfd 唤醒事件循环 —— 正确做法
//
// 客户端采用 burst 模式:所有连接同时把全部请求发出去再统一收响应。
// 只有这样才能体现"事件循环被卡住"对整个系统的伤害;若采用串行发请求,
// 测到的只是单连接往返延迟,看不出并发吞吐的差异。
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/epoll.h>
#include <sys/eventfd.h>
#include <sys/socket.h>
#include <fcntl.h>
#include <unistd.h>
#include <algorithm>
#include <atomic>
#include <chrono>
#include <condition_variable>
#include <cerrno>
#include <csignal>
#include <cstring>
#include <deque>
#include <functional>
#include <iostream>
#include <mutex>
#include <string>
#include <thread>
#include <vector>
using namespace std::chrono;
using namespace std::chrono_literals;
using std::chrono::microseconds;
static void set_nonblock(int fd) {
int fl = fcntl(fd, F_GETFL, 0);
fcntl(fd, F_SETFL, fl | O_NONBLOCK);
}
// 模拟一次"阻塞调用"。注意这里用 sleep_for 而非忙等:
// 同步 DB 客户端、磁盘 I/O、DNS 解析这类调用会让出 CPU,
// 若用忙等模拟,则线程池方案无法体现其优势(因为 CPU 才是瓶颈)。
static void blocking_call(double ms) {
std::this_thread::sleep_for(
duration<double, std::milli>(ms));
}
static std::atomic<bool> g_server_ready{false};
// ---------- 极简线程池:把"阻塞工作"搬出事件循环 ----------
struct Job { int fd; std::string req; };
struct Done { int fd; std::string resp; };
class WorkerPool {
public:
void start(int n, std::function<void()> on_done) {
on_done_ = on_done;
for (int i = 0; i < n; ++i)
threads_.emplace_back([this] {
for (;;) {
Job j;
{
std::unique_lock<std::mutex> lk(mu_);
cv_.wait(lk, [this] { return !q_.empty(); });
j = std::move(q_.front());
q_.pop_front();
}
blocking_call(5.0); // 阻塞调用现在发生在工作线程
{
std::lock_guard<std::mutex> lk(done_mu_);
done_.push_back({j.fd, j.req + "\n"});
}
on_done_(); // 通知事件循环:结果就绪
}
});
}
void submit(Job j) {
{ std::lock_guard<std::mutex> lk(mu_); q_.push_back(std::move(j)); }
cv_.notify_one();
}
std::vector<Done> drain() {
std::lock_guard<std::mutex> lk(done_mu_);
std::vector<Done> r = std::move(done_);
done_.clear();
return r;
}
private:
std::mutex mu_;
std::condition_variable cv_;
std::deque<Job> q_;
std::mutex done_mu_;
std::vector<Done> done_;
std::vector<std::thread> threads_;
std::function<void()> on_done_;
};
// ---------------- 服务端:单线程 epoll 事件循环 ----------------
// mode: 0=纯 echo 1=handler 内阻塞 2=阻塞工作交给线程池
void run_server(int port, int mode) {
signal(SIGPIPE, SIG_IGN);
int ln = socket(AF_INET, SOCK_STREAM, 0);
int one = 1;
setsockopt(ln, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
sockaddr_in addr{};
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
addr.sin_addr.s_addr = inet_addr("127.0.0.1");
if (bind(ln, (sockaddr *)&addr, sizeof(addr)) < 0) { perror("bind"); return; }
listen(ln, 4096);
set_nonblock(ln);
int ep = epoll_create1(0);
epoll_event e{};
e.events = EPOLLIN;
e.data.fd = ln;
epoll_ctl(ep, EPOLL_CTL_ADD, ln, &e);
// 跨线程唤醒 fd:工作线程干完活后写它,epoll_wait 立刻返回。
// 这正是 libev 的 ev_async / Boost.Asio 的 eventfd 唤醒机制的原理。
int wake = eventfd(0, EFD_NONBLOCK);
WorkerPool pool;
if (mode == 2) {
pool.start(4, [&] { uint64_t one_ = 1; (void)!write(wake, &one_, 8); });
epoll_event we{};
we.events = EPOLLIN;
we.data.fd = wake;
epoll_ctl(ep, EPOLL_CTL_ADD, wake, &we);
}
g_server_ready.store(true);
std::vector<epoll_event> evs(1024);
std::vector<std::string> inbuf(65536);
std::vector<std::string> outbuf(65536);
for (;;) {
int n = epoll_wait(ep, evs.data(), (int)evs.size(), -1);
for (int i = 0; i < n; ++i) {
int fd = evs[i].data.fd;
if (mode == 2 && fd == wake) { // 线程池完成:取回结果并写回
uint64_t v;
while (read(wake, &v, 8) > 0) { }
for (auto &d : pool.drain())
(void)!write(d.fd, d.resp.data(), d.resp.size());
continue;
}
if (fd == ln) { // 新连接:accept 到 EAGAIN
for (;;) {
int c = accept(ln, nullptr, nullptr);
if (c < 0) break;
set_nonblock(c);
if (c >= (int)inbuf.size()) {
inbuf.resize(c + 1024);
outbuf.resize(c + 1024);
}
inbuf[c].clear();
outbuf[c].clear();
epoll_event ce{};
ce.events = EPOLLIN;
ce.data.fd = c;
epoll_ctl(ep, EPOLL_CTL_ADD, c, &ce);
}
continue;
}
// 已连接 socket:读取(水平触发 LT)
char buf[4096];
for (;;) {
ssize_t r = read(fd, buf, sizeof(buf));
if (r > 0) { inbuf[fd].append(buf, r); continue; }
if (r == 0) { // 对端关闭
epoll_ctl(ep, EPOLL_CTL_DEL, fd, nullptr);
::close(fd);
break;
}
if (errno == EAGAIN || errno == EWOULDBLOCK) break; // 本轮读完
epoll_ctl(ep, EPOLL_CTL_DEL, fd, nullptr);
::close(fd);
break;
}
// 处理:每收到一个完整行(以 '\n' 结尾)就产生一个响应
size_t pos;
while ((pos = inbuf[fd].find('\n')) != std::string::npos) {
std::string req = inbuf[fd].substr(0, pos);
inbuf[fd].erase(0, pos + 1);
if (mode == 0) {
outbuf[fd] += req + "\n"; // A:立即完成
} else if (mode == 1) {
blocking_call(5.0); // B:★阻塞在事件循环线程
outbuf[fd] += req + "\n";
} else {
pool.submit({fd, req}); // C:★交给线程池,立即返回
}
}
if (!outbuf[fd].empty()) {
ssize_t w = write(fd, outbuf[fd].data(), outbuf[fd].size());
if (w > 0) outbuf[fd].erase(0, w);
}
}
}
}
int main(int argc, char **argv) {
int nconn = argc > 1 ? std::atoi(argv[1]) : 50;
int nreq = argc > 2 ? std::atoi(argv[2]) : 20;
int mode = 0;
if (argc > 3) {
std::string m = argv[3];
if (m == "slow") mode = 1;
else if (m == "pool") mode = 2;
}
int port = 18800 + (getpid() % 1000);
std::thread srv(run_server, port, mode);
srv.detach();
while (!g_server_ready.load()) std::this_thread::sleep_for(milliseconds(5));
std::this_thread::sleep_for(milliseconds(50));
// ---------------- 建立 nconn 条连接 ----------------
std::vector<int> fds;
for (int i = 0; i < nconn; ++i) {
int fd = socket(AF_INET, SOCK_STREAM, 0);
sockaddr_in a{};
a.sin_family = AF_INET;
a.sin_port = htons(port);
a.sin_addr.s_addr = inet_addr("127.0.0.1");
if (connect(fd, (sockaddr *)&a, sizeof(a)) < 0) { perror("connect"); return 1; }
fds.push_back(fd);
}
// ---------------- 客户端:burst 并发模式 ----------------
// 所有连接同时把全部请求发出,再统一收集响应。只有这样才能体现
// "事件循环被卡住"对整个系统的伤害 —— 若改成串行地"发一个等一个",
// 客户端自身成为串行瓶颈,服务端并行度再高也无法体现。
for (int fd : fds) set_nonblock(fd);
std::vector<int> sent(nconn, 0), recvd(nconn, 0);
std::vector<std::string> cbuf(nconn);
std::vector<double> first_resp(nconn, -1.0);
auto t0 = steady_clock::now();
bool done = false;
while (!done) {
done = true;
for (int i = 0; i < nconn; ++i) {
int fd = fds[i];
while (sent[i] < nreq) { // 发,直到 EAGAIN
ssize_t w = write(fd, "ping\n", 5);
if (w > 0) { ++sent[i]; continue; }
break;
}
for (;;) { // 收,直到 EAGAIN
char b[256];
ssize_t r = read(fd, b, sizeof(b));
if (r <= 0) break;
cbuf[i].append(b, r);
size_t p;
// 必须按 '\n' 计数,不能按 read 次数计数 ——
// 一次 read 可能读到多个响应,按次数计数会导致永远收不满。
while ((p = cbuf[i].find('\n')) != std::string::npos) {
if (first_resp[i] < 0)
first_resp[i] =
duration<double, std::milli>(steady_clock::now() - t0).count();
++recvd[i];
cbuf[i].erase(0, p + 1);
}
}
if (recvd[i] < nreq) done = false;
}
if (!done) std::this_thread::sleep_for(microseconds(300));
}
double total = duration<double, std::milli>(steady_clock::now() - t0).count();
std::sort(first_resp.begin(), first_resp.end());
auto pct = [&](double q) {
return first_resp[std::min((size_t)(first_resp.size() * q),
first_resp.size() - 1)];
};
const char *name =
mode == 0 ? "A: handler 很轻(纯 echo)"
: mode == 1 ? "B: handler 内有 5ms 阻塞调用(反例)"
: "C: 阻塞工作交给线程池 + eventfd 唤醒";
std::cout << "模式: " << name
<< " 连接数=" << nconn << " 每连接请求数=" << nreq
<< " 总请求数=" << (nconn * nreq) << "\n"
<< " 总耗时 " << total << " ms 吞吐 "
<< (nconn * nreq) / (total / 1000.0) << " req/s\n"
<< " 首个响应到达延迟 p50=" << pct(0.50) << " ms p99=" << pct(0.99)
<< " ms max=" << first_resp.back() << " ms\n\n";
for (int fd : fds) ::close(fd);
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。