eventfd 线程唤醒
Eventfd Thread Wakeup
题目详情
高频交易系统常使用轻量级通知机制配合固定大小环形缓冲区实现线程间快速无锁数据传输。此架构最小化延迟和避免动态分配开销。eventfd 提供比传统 pipe 更高效的单值通知。
任务:实现 EventQueue 类,使用 eventfd 作为线程唤醒信号配合环形缓冲区存储数据。生产者 push 数据到环形缓冲区并通过 eventfd 通知消费者,消费者 epoll_wait 等待通知后 pop 数据。
英文原题
High-frequency trading systems often utilize lightweight notification mechanisms combined with fixed-size circular buffers to facilitate rapid, lock-free data transfer between threads. This architecture minimizes latency and avoids dynamic allocation overhead by maintaining deterministic memory access patterns. Simulating this behavior involves managing a ring buffer for data storage and an event counter to signal pending work to consumers.
Task
Implement a class NotificationSystem that manages
解析
问题分析
eventfd 是 Linux 提供的轻量级事件通知机制,比管道开销更低。在交易系统中用于线程间的唤醒信号——例如当新订单到达时,通过 eventfd 唤醒处理线程。
实现
class EventFd {
int fd_;
public:
EventFd() : fd_(::eventfd(0, EFD_NONBLOCK | EFD_SEMAPHORE)) {}
void notify(uint64_t count = 1) { ::write(fd_, &count, sizeof(count)); }
bool wait() {
uint64_t val;
return ::read(fd_, &val, sizeof(val)) > 0; // 非阻塞,无事件返回 false
}
int fd() const { return fd_; }
~EventFd() { ::close(fd_); }
};复杂度与边界
- 时间复杂度:notify/wait O(1) 系统调用
- 空间复杂度:O(1)
- 边界条件:(1) EFD_SEMAPHORE 模式下每次 read 减 1 (2) 内核 2.6.27+ (3) 配合 epoll 使用实现高效事件循环
英文解析
Analysis
eventfd is a lightweight event notification mechanism provided by Linux, with lower overhead than pipes. In trading systems, it is used for inter-thread wakeup signals - for example, waking up a processing thread when a new order arrives.
Solution
class EventFd {
int fd_;
public:
EventFd() : fd_(::eventfd(0, EFD_NONBLOCK | EFD_SEMAPHORE)) {}
void notify(uint64_t count = 1) { ::write(fd_, &count, sizeof(count)); }
bool wait() {
uint64_t val;
return ::read(fd_, &val, sizeof(val)) > 0; // Non-blocking, returns false if no event
}
int fd() const { return fd_; }
~EventFd() { ::close(fd_); }
};Complexity & Edge Cases
- Time complexity: notify/wait O(1) system call
- Space complexity: O(1)
- Edge cases: (1) In EFD_SEMAPHORE mode, each read decrements by 1 (2) Requires kernel 2.6.27+ (3) Combined with epoll for efficient event loops
Verification
Test notify/wait across threads. Verify EFD_SEMAPHORE semantics (each read consumes one count). Integrate with epoll event loop and confirm wakeup latency.
Key Considerations
eventfd is the preferred wakeup mechanism for event-driven trading systems. Combined with epoll, it enables a single-threaded event loop that processes market data, orders, and timer events - each wakeup source (data feed, order entry, timer) uses its own eventfd for clean separation of concerns.