当前位置: 首页 > article >正文

内核定时器3-用户空间定时器

用户空间定时器与内核定时器的关系

虽然用户空间定时器和内核定时器在实现上各自独立,但用户空间定时器通常依赖于内核定时器提供的基础设施。以下是具体关系:

  1. 依赖性
    • 用户空间定时器的实现基于内核定时器。
      • 例如,POSIX 定时器使用内核的 hrtimer 机制。
      • alarm()setitimer() 使用内核低精度定时器。
    • 内核通过用户态 API(如 timerfdclock_nanosleep())将定时器功能暴露给用户空间。
  2. 精度
    • 用户空间定时器的精度取决于内核定时器的支持:
      • 在启用高分辨率定时器(CONFIG_HIGH_RES_TIMERS=y)时,用户空间定时器可以实现亚毫秒级精度。
      • 如果系统只支持低分辨率定时器,用户空间定时器的精度会受到限制(分辨率基于HZjiffies)。
  3. 隔离性
    • 内核定时器运行在内核态,直接管理硬件资源,对用户态透明。
    • 用户空间定时器运行在用户态,通过系统调用访问内核资源。
  4. 性能
    • 内核定时器的执行效率更高,因为它直接操作硬件并在内核上下文中运行。
    • 用户空间定时器的执行效率相对较低,因其需要从用户态切换到内核态并依赖系统调用。

用户空间定时器

在 Linux 中,用户空间有多种方式可以使用定时器来执行定时任务或管理延时操作。以下是常见的方法及其详细说明:  

1. 使用 **alarm()** 函数

  • 功能:
    • alarm() 用于设置一个定时器,定时结束时会向当前进程发送 SIGALRM 信号。
  • 用法:
#include <unistd.h>
#include <signal.h>
#include <stdio.h>

void alarm_handler(int sig) {
    printf("Alarm triggered!\n");
}

int main() {
    signal(SIGALRM, alarm_handler); // 设置信号处理函数
    alarm(5); // 设置定时器,5秒后触发
    pause();  // 等待信号
    return 0;
}
  • 特点:
    • 简单易用。
    • 只能设置秒级的定时器。
    • 只能设置一个定时器。
    • 定时器到期后,如果是多线程,会选择一个当前非阻塞的线程来处理信号,处理线程并不确定
  • 依赖的内核机制
    • 依赖于**内核 jiffies,**即低分辨率定时器。
    • 内核定时器队列(timer_list)会管理这些定时器,触发时发送信号。

2. 使用 **setitimer()** 函数

  • 功能:
    • setitimer() 可以设置定时器,以精确控制一次性或周期性的定时任务。
    • 当定时时间到达时,会向调用进程发送信号(通常是 SIGALRM)。
  • 用法:
#include <sys/time.h>
#include <signal.h>
#include <stdio.h>

void timer_handler(int sig) {
    printf("Timer triggered!\n");
}

int main() {
    struct itimerval timer;
    signal(SIGALRM, timer_handler); // 设置信号处理函数

    // 定时器间隔为1秒
    timer.it_value.tv_sec = 1;
    timer.it_value.tv_usec = 0;
    timer.it_interval.tv_sec = 1;
    timer.it_interval.tv_usec = 0;

    setitimer(ITIMER_REAL, &timer, NULL); // 设置定时器
    while (1); // 无限循环等待定时器触发
    return 0;
}
  • 特点:
    • 支持周期性定时器。
    • 提供微秒级别的精度。
  • 依赖的内核机制
    • 本身最初是设计为基于低分辨率定时器,但在现代内核中,如果高分辨率定时器启用,它可以利用高分辨率定时器来提高精度
    • 内核定时器队列(timer_list)会管理这些定时器,触发时发送信号。

3. 使用 POSIX 定时器 (**timer_create()**** 和 **timer_settime()**)**

  • 功能:
    • POSIX 定时器提供了灵活的定时功能,可以通过多种方式通知(如信号或回调)。
    • 可以创建多个定时器。
    • 使用 timer_create() 创建一个定时器,时间到达时触发信号或调用特定的回调函数。
  • 用法:
    • **timer_create**:
      • 用于创建一个 POSIX 定时器。
      • 可以选择通知方式,包括发送信号(SIGEV_SIGNAL)和使用线程回调(SIGEV_THREAD)。
    • **timer_settime**:
      • 用于设置定时器的到期时间 (it_value) 和周期性时间 (it_interval)。
    • 定时器的通知方式:
      • SIGEV_SIGNAL: 定时器超时时发送指定信号(如 SIGALRM)。
      • SIGEV_THREAD: 定时器超时时调用用户定义的回调函数。
// gcc -o posix_timer posix_timer.c -lrt -pthread

#include <time.h>
#include <signal.h>
#include <stdio.h>

void timer_handler(union sigval sv) {
    printf("POSIX timer triggered![%ld]\n", pthread_self());
}

int main() {
    timer_t timerid;
    struct sigevent sev;
    struct itimerspec ts;

    sev.sigev_notify = SIGEV_THREAD; // 使用线程通知方式
    sev.sigev_value.sival_ptr = &timerid;
    sev.sigev_notify_function = timer_handler;
    sev.sigev_notify_attributes = NULL;

    timer_create(CLOCK_REALTIME, &sev, &timerid);

    ts.it_value.tv_sec = 2;  // 初始触发时间
    ts.it_value.tv_nsec = 0;
    ts.it_interval.tv_sec = 2;  // 周期触发时间
    ts.it_interval.tv_nsec = 0;

    timer_settime(timerid, 0, &ts, NULL);

    while (1); // 等待定时器触发
    return 0;
}

可以看到有两个线程,一个main线程,一个回调线程

$ #ps -eLf | grep posix_timer
congchp  1965725 1138860 1965725 99    2 11:11 pts/4    00:02:27 ./posix_timer
congchp  1965725 1138860 1965726  0    2 11:11 pts/4    00:00:00 ./posix_timer
congchp  1966341  939085 1966341  0    1 11:13 pts/2    00:00:00 grep --color=auto posix_timer
  • 特点:
    • 支持多个定时器。
    • 支持多种通知方式(如线程回调或信号)。
    • 通知方式如果使用SIGEV_THREAD,则自动创建一个回调线程。
  • 依赖的内核机制
    • 内核使用 hrtimer(高精度定时器)实现。
    • hrtimer 基于内核的高精度时间子系统,支持纳秒级别的精度。
    • 事件触发通过 softirq 或中断机制实现。

4. 使用 **sleep()** **nanosleep()**``**clock_nanosleep()** 函数

  • 功能
    • 这些函数用于让进程挂起一定时间。
    • sleep() 提供秒级精度,而 nanosleep()clock_nanosleep() 提供纳秒级精度。
    • 可以被信号(如Ctrl+C)打断

※Ctrl+C后,先发送SIGINT,如果SIGINT没有被处理,则发送SIGKILL强制终止进程。

  • 用法:
#include <stdio.h>
#include <time.h>
#include <signal.h>
#include <stdlib.h>

void handle_sigint(int sig) {
    printf("Received SIGINT (Ctrl+C). Exiting...\n");
}

int main() {
    struct timespec req, rem;
    req.tv_sec = 2;  // Sleep for 2 seconds
    req.tv_nsec = 500000000;  // Plus 500 milliseconds

    // 设置自定义信号处理函数
    signal(SIGINT, handle_sigint);

    printf("Sleeping for 2.5 seconds...\n");

    if (nanosleep(&req, &rem) == -1) {
        perror("nanosleep interrupted");
        printf("%ld.%ld remain\n", rem.tv_sec, rem.tv_nsec);
        return 1;
    }
    printf("Sleep complete!\n");

    return 0;
}

  • 依赖的内核机制
    • 使用hrtimer(高精度定时器)进行时间跟踪。
    • 内核会将进程标记为睡眠状态,定时时间到后通过唤醒机制让进程继续运行。

5. **使用 ****poll()**/select()/epoll()的超时功能

  • 功能
    • 提供 I/O 多路复用时的超时功能(timeout),用于等待文件描述符的状态变化。
    • 这些函数可以设置超时时间,如果没有检测到IO,让调用线程挂起指定时间。
  • 用法:
#include <stdio.h>
#include <poll.h>
#include <unistd.h>

int main() {
    struct pollfd fds[1];
    fds[0].fd = STDIN_FILENO;  // Monitor standard input
    fds[0].events = POLLIN;

    int timeout = 5000;  // 5-second timeout

    printf("Waiting for input (5 seconds timeout)...\n");
    int ret = poll(fds, 1, timeout);

    if (ret == -1) {
        perror("poll failed");
    } else if (ret == 0) {
        printf("Timeout occurred!\n");
    } else if (fds[0].revents & POLLIN) {
        char buffer[100];
        read(STDIN_FILENO, buffer, sizeof(buffer));
        printf("Input received: %s", buffer);
    }

    return 0;
}
  • 特点:
    • 高效且支持事件驱动(如结合 epoll)。
    • 适用于文件描述符管理的场景。
  • 依赖的内核机制
    • 高分辨率定时器启用的情况下,使用hrtimer;否则使用tick-based定时器,取决于内核配置和硬件支持。
    • 内核会将调用线程加入等待队列,并在超时到期或事件发生时唤醒线程。

6. 使用 **timerfd** 接口

  • 功能
    • **timerfd**: 通过文件描述符(FD)暴露定时器事件,适合与 epoll 一起使用。
    • read()函数读取出来的,自上一次读取以来的所有未处理的超期次数。
  • 用法:
#include <sys/timerfd.h>
#include <unistd.h>
#include <stdio.h>
#include <stdint.h>

int main() {
    int tfd = timerfd_create(CLOCK_REALTIME, 0);
    struct itimerspec ts;
    ts.it_value.tv_sec = 2; // 初始触发时间
    ts.it_value.tv_nsec = 0;
    ts.it_interval.tv_sec = 2; // 周期触发时间
    ts.it_interval.tv_nsec = 0;

    timerfd_settime(tfd, 0, &ts, NULL);

    uint64_t expirations;
    while (1) {
        read(tfd, &expirations, sizeof(expirations)); // 阻塞等待
        printf("Timer expired %lu times\n", expirations); // expirations = 1
    }
    close(tfd);
    return 0;
}
  • 特点:
    • 高效且支持事件驱动(如结合 epoll)。
    • 适用于大量定时器、文件描述符管理的场景。
  • 依赖的内核机制
    • timerfd 基于内核的 hrtimer 实现。
    • 内核将定时器事件封装为文件描述符事件,通过 VFS 层传递给用户空间。

对比各种方法

方法多定时器支持周期性定时器精度内核机制易用性推荐用途
alarm()秒级低分辨率定时器简单单一的短时任务
setitimer()微秒级低分辨率定时器较简单简单的周期性任务
POSIX 定时器纳秒级高分辨率定时器较复杂多任务,灵活的通知方式
sleep()
/nanosleep()
秒级/纳秒低/高分辨率定时器简单简单的延时任务
poll()/select()/epoll()毫秒级高分辨率定时器较复杂高效的文件描述符管理场景
timerfd纳秒级高分辨率定时器较复杂高效的文件描述符管理场景

根据需求选择合适的定时器接口,可以满足不同的用户空间定时任务需求。


timerfd+IO多路复用组合使用

※※※ 推荐的方法,是**timerfd**+**IO多路复用**组合使用的方法。

#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <sys/timerfd.h>
#include <sys/epoll.h>
#include <string.h>
#include <stdint.h>
#include <fcntl.h>
#include <mqueue.h>
#include <sched.h>

#define MAX_EVENTS 10
#define WORKER_COUNT 2
#define QUEUE_NAME "/task_queue"

// 任务结构
typedef struct {
    int task_id;
} Task;

// 线程信息
typedef struct {
    mqd_t mqd;
    pthread_t thread;
    int id;
} WorkerThread;

WorkerThread workers[WORKER_COUNT];

// 任务回调
void task_callback(int task_id) {
    printf("Worker processing task %d\n", task_id);
    sleep(1);  // 模拟任务执行
}

// 设定线程优先级
void set_thread_priority(pthread_t thread, int priority) {
    struct sched_param param;
    param.sched_priority = priority;
    pthread_setschedparam(thread, SCHED_FIFO, &param);
}

// 工作线程函数
void *worker_thread(void *arg) {
    WorkerThread *worker = (WorkerThread *)arg;
    Task task;
    while (1) {
        if (mq_receive(worker->mqd, (char *)&task, sizeof(Task), NULL) > 0) {
            task_callback(task.task_id);
        }
    }
}

// 选择负载最轻的工作线程
WorkerThread *get_least_busy_worker() {
    struct mq_attr attr;
    WorkerThread *best_worker = &workers[0];

    for (int i = 1; i < WORKER_COUNT; i++) {
        mq_getattr(workers[i].mqd, &attr);
        struct mq_attr best_attr;
        mq_getattr(best_worker->mqd, &best_attr);
        if (attr.mq_curmsgs < best_attr.mq_curmsgs) {
            best_worker = &workers[i];
        }
    }
    return best_worker;
}

// 定时器检测线程
void *timer_thread(void *arg) {
    set_thread_priority(pthread_self(), 90);

    int epfd = epoll_create1(0);
    int timerfd = timerfd_create(CLOCK_REALTIME, 0);
    struct itimerspec timer_value = {
        .it_value = {2, 0},  
        .it_interval = {3, 0} 
    };
    timerfd_settime(timerfd, 0, &timer_value, NULL);

    struct epoll_event ev;
    ev.events = EPOLLIN;
    ev.data.fd = timerfd;
    epoll_ctl(epfd, EPOLL_CTL_ADD, timerfd, &ev);

    while (1) {
        struct epoll_event events[MAX_EVENTS];
        int nfds = epoll_wait(epfd, events, MAX_EVENTS, -1);
        for (int i = 0; i < nfds; i++) {
            if (events[i].data.fd == timerfd) {
                uint64_t exp;
                read(timerfd, &exp, sizeof(uint64_t));
                printf("Timer expired! Dispatching task...\n");

                static int task_id = 0;
                Task task = {task_id++};

                WorkerThread *worker = get_least_busy_worker();
                mq_send(worker->mqd, (char *)&task, sizeof(Task), 0);
            }
        }
    }
}

// 主程序
int main() {
    struct mq_attr attr = {
        .mq_flags = 0,
        .mq_maxmsg = 10,
        .mq_msgsize = sizeof(Task),
        .mq_curmsgs = 0
        };

    // 初始化工作线程
    for (int i = 0; i < WORKER_COUNT; i++) {
        workers[i].id = i;
        workers[i].mqd = mq_open(QUEUE_NAME, O_CREAT | O_RDWR | O_NONBLOCK, 0644, &attr);
        pthread_create(&workers[i].thread, NULL, worker_thread, &workers[i]);
        set_thread_priority(workers[i].thread, 80);
    }

    // 启动定时器检测线程
    pthread_t timer_tid;
    pthread_create(&timer_tid, NULL, timer_thread, NULL);
    pthread_join(timer_tid, NULL);

    for (int i = 0; i < WORKER_COUNT; i++) {
        pthread_join(workers[i].thread, NULL);
        mq_close(workers[i].mqd);
    }
    mq_unlink(QUEUE_NAME);
    return 0;
}



还有一些定时器数据结构设计方法,参考之前另一篇定时器文章:《定时器实现》


http://www.kler.cn/a/531069.html

相关文章:

  • 【Linux】从硬件到软件了解进程
  • 蓝桥杯备赛经验帖
  • 使用 PyTorch 实现逻辑回归并评估模型性能
  • Linux网络 HTTPS 协议原理
  • 13 尺寸结构模块(size.rs)
  • model calibration
  • Docker Hub 镜像 Pull 失败的解决方案
  • AJAX笔记进阶篇
  • 《使用Ollama部署DeepSeek并进行对话全过程记录》
  • Spring 面试题【每日20道】【其二】
  • 11.1 LangChain Chains 最佳实践:从流水线设计到生产部署的全链路指南
  • 35.Word:公积金管理中心文员小谢【37】
  • string例题
  • MYSQL性能调优连接器、查询缓存、分析器、优化器、执行器、一图详解MYSQL底层工作原理
  • 泰山Office开源计划
  • 机试题——字符匹配
  • Python的那些事第十篇:隐藏细节与提供接口的艺术Python中的封装
  • Leetcode—598. 区间加法 II【简单】
  • golang命令大全7--性能优化与分析
  • Vue - readonly 与 shallowReadonly
  • 模拟实战-用CompletableFuture优化远程RPC调用
  • 【优先算法】专题——位运算
  • 存储器知识点2
  • 基础IO的学习
  • 代码随想录-训练营-day18
  • 【go语言】grpc 快速入门