计算机网络 / 系统课时

跨线程唤醒为什么需要事件fd

跨线程唤醒为什么需要事件fd

Reactor 线程常常阻塞在 epoll_wait,而业务线程又会异步产生“发送数据、关闭连接、更新订阅”等任务。本节解决的核心问题是:如何让业务线程只负责投递任务,并可靠唤醒 I/O 线程,由 Reactor 在自己的线程中完成真正的连接操作。

学习目标

  • 解释共享队列本身为什么不能唤醒阻塞中的 epoll_wait
  • 使用 eventfd 把跨线程通知转换成 Reactor 可监听的文件描述符事件
  • 识别任务队列、通知计数与边沿触发模式中的常见竞态

Reactor 为什么不能只轮询共享队列

业务线程把任务放进并发队列后,Reactor 线程可能仍睡在 epoll_wait 中。单纯让 Reactor 周期性轮询队列,要么把超时时间设得很短并持续消耗 CPU,要么超时时间较长而增加任务响应延迟。

条件变量虽然适合线程同步,却不能直接加入 epoll。管道也能承担唤醒职责,但跨线程通知只需要“有新工作”这一件事时,Linux 的 eventfd 更直接:它在内核中维护一个 64 位计数器,同时表现为普通文件描述符,因此可以和 socket 一起注册到 epoll。

eventfd 跨线程唤醒 Reactor 的数据流

eventfd 把通知变成 I/O 事件

创建时通常使用 EFD_NONBLOCK | EFD_CLOEXEC。业务线程每次投递后写入一个 uint64_t 的 1;只要计数器大于 0,eventfd 就处于可读状态。没有启用 EFD_SEMAPHORE 时,一次 read 会取出当前累计值并把计数器归零,因此多次唤醒可以自然合并。

这里最重要的顺序是先入队,再通知。如果先写 eventfd,Reactor 可能先被唤醒并发现队列为空,随后业务线程才真正入队,任务就可能一直等到下一次事件。eventfd 不是任务队列,它只负责告诉 Reactor“队列里可能有工作”。

一个最小可运行的跨线程投递

下面的程序用互斥锁保护一个小型队列。生产线程依次放入三个任务和一个停止标记;Reactor 同时监听 eventfd,收到通知后把队列一次取空。

c
#include <errno.h>
#include <pthread.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/epoll.h>
#include <sys/eventfd.h>
#include <unistd.h>

#define CAPACITY 16

static int event_fd;
static int tasks[CAPACITY];
static size_t head = 0;
static size_t tail = 0;
static pthread_mutex_t queue_mutex = PTHREAD_MUTEX_INITIALIZER;

static void submit_task(int value) {
    pthread_mutex_lock(&queue_mutex);
    if (tail - head >= CAPACITY) {
        pthread_mutex_unlock(&queue_mutex);
        fprintf(stderr, "task queue full\n");
        exit(EXIT_FAILURE);
    }
    tasks[tail % CAPACITY] = value;
    ++tail;
    pthread_mutex_unlock(&queue_mutex);

    // 任务必须先发布到队列,再发送唤醒通知。
    uint64_t one = 1;
    if (write(event_fd, &one, sizeof(one)) != sizeof(one)) {
        perror("write eventfd");
        exit(EXIT_FAILURE);
    }
}

static int pop_task(int *value) {
    int found = 0;
    pthread_mutex_lock(&queue_mutex);
    if (head < tail) {
        *value = tasks[head % CAPACITY];
        ++head;
        found = 1;
    }
    pthread_mutex_unlock(&queue_mutex);
    return found;
}

static void *producer(void *arg) {
    (void)arg;
    submit_task(101);
    submit_task(102);
    submit_task(103);
    submit_task(-1);
    return NULL;
}

int main(void) {
    event_fd = eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC);
    int epoll_fd = epoll_create1(EPOLL_CLOEXEC);
    if (event_fd == -1 || epoll_fd == -1) {
        perror("create fd");
        return EXIT_FAILURE;
    }

    struct epoll_event ev = {.events = EPOLLIN, .data.fd = event_fd};
    if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, event_fd, &ev) == -1) {
        perror("epoll_ctl");
        return EXIT_FAILURE;
    }

    pthread_t thread;
    if (pthread_create(&thread, NULL, producer, NULL) != 0) {
        perror("pthread_create");
        return EXIT_FAILURE;
    }

    int running = 1;
    while (running) {
        struct epoll_event events[4];
        int ready = epoll_wait(epoll_fd, events, 4, -1);
        if (ready == -1 && errno == EINTR) {
            continue;
        }
        if (ready == -1) {
            perror("epoll_wait");
            return EXIT_FAILURE;
        }

        for (int i = 0; i < ready; ++i) {
            if (events[i].data.fd != event_fd) {
                continue;
            }

            // 非阻塞模式下读到 EAGAIN 才表示本轮通知已经清空。
            for (;;) {
                uint64_t count;
                ssize_t n = read(event_fd, &count, sizeof(count));
                if (n == sizeof(count)) {
                    continue;
                }
                if (n == -1 && errno == EAGAIN) {
                    break;
                }
                perror("read eventfd");
                return EXIT_FAILURE;
            }

            int task;
            while (pop_task(&task)) {
                if (task == -1) {
                    running = 0;
                    break;
                }
                printf("handle task %d\n", task);
            }
        }
    }

    pthread_join(thread, NULL);
    close(epoll_fd);
    close(event_fd);
    puts("reactor stopped");
    return EXIT_SUCCESS;
}

把源码保存为 wakeup.c 后编译并运行:

bash
cc -O2 -Wall -Wextra -pthread wakeup.c -o wakeup && ./wakeup

预期输出:

text
handle task 101
handle task 102
handle task 103
reactor stopped

eventfd 的累计值是否一次读到 1、2 还是 4 取决于调度时机,因此示例不把通知次数当作业务语义;真正需要处理的是队列中的任务。

生产实现需要守住的边界

Reactor 被唤醒后应当把任务队列取到当前为空,因为多个通知可能已经被 eventfd 合并。若把 eventfd 注册为 EPOLLET,还必须把该描述符读到 EAGAIN,否则可能丢失后续边沿。

关闭流程也要有所有权:先停止生产者或拒绝新任务,再唤醒 Reactor 完成剩余任务,最后由拥有该描述符的线程关闭 eventfd。如果业务线程还能继续写,而 Reactor 已经关闭描述符,就会进入典型的生命周期竞态。

当任务量很大时,通常把“任务数据”和“唤醒信号”分开设计:MPSC 队列负责承载任务,eventfd 只负责把睡眠中的 Reactor 拉回事件循环。这样既避免忙轮询,又能保持所有 socket 状态仍由单一 I/O 线程串行修改。

按自己的节奏,确认真正理解。

目录与阅读设置

阅读设置

17

记录一个想法

跨线程唤醒为什么需要事件fd

0 / 10000 · 笔记保存到账号。未提交的修改会在关闭、离开或刷新后丢失。

登录哪都通