Linux多线程编程 - sleep 和 pthread_cond_timedwait
#include <stdio.h>
#include <stdlib.h>
int flag = 1;
void * thr_fn(void * arg)
{
while (flag)
{
printf("******\n");
sleep(10);
}
printf("sleep test thread exit\n");
}
int main()
{
pthread_t thread;
if (0 != pthread_create(&thread, NULL, thr_fn, NULL))
{
printf("error when create pthread,%d\n", errno);
return 1;
}
char c ;
while ((c = getchar()) != 'q');
printf("Now terminate the thread!\n");
flag = 0;
printf("Wait for thread to exit\n");
pthread_join(thread, NULL);
printf("Bye\n"); return 0;
}
输入q后,需要等线程从sleep中醒来(由挂起状态变为运行状态),即最坏情况要等10s,线程才会被join。采用sleep的缺点:不能及时唤醒线程。
采用pthread_cond_timedwait函数,条件到了,线程即会被join,可及时唤醒线程。实现的如下:
#include <stdio.h> #include <sys/time.h> #include <unistd.h> #include <pthread.h> #include <errno.h> static pthread_t thread; static pthread_cond_t cond; static pthread_mutex_t mutex; static int flag = 1; void * thr_fn(void * arg) { struct timeval now; struct timespec outtime; pthread_mutex_lock(&mutex); while (flag) { printf("*****\n"); gettimeofday(&now, NULL); outtime.tv_sec = now.tv_sec + 5; outtime.tv_nsec = now.tv_usec * 1000; pthread_cond_timedwait(&cond, &mutex, &outtime); } pthread_mutex_unlock(&mutex); printf("cond thread exit\n"); } int main(void) { pthread_mutex_init(&mutex, NULL); pthread_cond_init(&cond, NULL); if (0 != pthread_create(&thread, NULL, thr_fn, NULL)) { printf("error when create pthread,%d\n", errno); return 1; } char c ; while ((c = getchar()) != 'q'); printf("Now terminate the thread!\n"); pthread_mutex_lock(&mutex); flag = 0; pthread_cond_signal(&cond); pthread_mutex_unlock(&mutex); printf("Wait for thread to exit\n"); pthread_join(thread, NULL); printf("Bye\n"); return 0; } |
pthread_cond_timedwait()函数阻塞住调用该函数的线程,等待由cond指定的条件被触发(pthread_cond_broadcast() or pthread_cond_signal())。
当pthread_cond_timedwait()被调用时,调用线程必须已经锁住了mutex。函数pthread_cond_timedwait()会对mutex进行【解锁和执行对条件的等待】(原子操作)。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?