如何用C语言实现两个线程分别以10ms、20ms为周期定时执行
实现周期性线程的方案
要实现两个线程分别按10ms、20ms周期执行,最简便稳定的方案是在线程函数内增加循环和休眠逻辑,无需额外引入定时器组件,避免信号处理的兼容性问题。
关键修改点
- 原线程函数仅执行一次就会退出,需改为无限循环结构,每次执行业务逻辑后休眠对应周期间隔
- 引入
nanosleep实现高精度休眠,精度可以达到纳秒级,比usleep更适合毫秒级的周期控制 - main函数末尾增加
pthread_join调用,阻塞等待子线程运行,避免主函数直接退出导致整个进程终止 - 修复原代码语法问题:
exit()需传入退出状态码,printf增加换行符刷新输出缓冲区,避免内容停留在缓冲区看不到打印结果
完整可运行代码
#include <stdio.h> #include <stdlib.h> #include <pthread.h> #include <time.h> void *t1(){ long tid = 9; // 配置休眠时长:10ms = 10 * 1000000 纳秒 struct timespec ts = {.tv_sec = 0, .tv_nsec = 10 * 1000000}; while(1) { printf("thread ID %ld\n", tid); nanosleep(&ts, NULL); // 若需要规避业务执行时长占用周期,可在此处计算实际执行耗时调整ts的值 } } void *t2(){ long tid = 10; // 配置休眠时长:20ms struct timespec ts = {.tv_sec = 0, .tv_nsec = 20 * 1000000}; while(1) { printf("thread ID %ld\n", tid); nanosleep(&ts, NULL); } } int main() { pthread_t thread1, thread2; int rc; rc = pthread_create(&thread1, NULL, t1, NULL); if(rc) { printf("ERROR\n"); exit(-1); } rc = pthread_create(&thread2, NULL, t2, NULL); if(rc) { printf("ERROR\n"); exit(-1); } // 等待子线程执行,不会主动返回 pthread_join(thread1, NULL); pthread_join(thread2, NULL); return 0; }
补充说明
如果必须使用定时器触发执行,可以使用POSIX标准的timer_create接口创建定时器,绑定指定信号的处理函数为对应业务逻辑,需要注意设置线程信号掩码,避免信号被其他线程捕获,实现复杂度更高,无特殊精度要求时优先使用上述线程内休眠的方案。
内容的提问来源于stack exchange,提问作者arc
相关产品推荐
相关产品推荐

