没有合适的资源?快使用搜索试试~ 我知道了~
Linux多线程编程,替代sleep的几种方式
9 下载量 173 浏览量
2021-01-09
14:45:39
上传
评论 1
收藏 53KB PDF 举报
温馨提示
试读
2页
我只想要进程的某个线程休眠一段时间的,可是用sleep()是将整个进程都休眠的,这个可能达不到,我们想要的效果了。目前我知道有三种方式: 1、usleep 这个是轻量级的,听说能可一实现线程休眠,我个人并不喜欢这种方式,所以我没有验证它的可行信(个人不推荐)。 2、select 这个可以,我也用过这种方式,它是在轮询。 3、pthread_cond_timedwait 采用pthread_cond_timedwait(pthread_cond_t* cond, pthread_mutex_t *mutex, const struct timesp
资源推荐
资源详情
资源评论
Linux多线程编程,替代多线程编程,替代sleep的几种方式的几种方式
我只想要进程的某个线程休眠一段时间的,可是用sleep()是将整个进程都休眠的,这个可能达不到,我们想要的效果
了。目前我知道有三种方式:
1、usleep
这个是轻量级的,听说能可一实现线程休眠,我个人并不喜欢这种方式,所以我没有验证它的可行信(个人不推荐)。
2、select
这个可以,我也用过这种方式,它是在轮询。
3、pthread_cond_timedwait
采用pthread_cond_timedwait(pthread_cond_t* cond, pthread_mutex_t *mutex, const struct timespec *abstime)可以
优雅的解决该问题,设置等待条件变量cond,如果超时,则返回;如果等待到条件变量cond,也返回。本文暂不将内部机
理,仅演示一个demo。
首先,看这段代码,thr_fn为一个线程函数:
#include <stdio.h>
#include <stdlib.h>
int flag = 1;
void * thr_fn(void * arg) {
while (flag){
printf("******
");
sleep(10);
}
printf("sleep test thread exit
");
}
int main() {
pthread_t thread;
if (0 != pthread_create(&thread, NULL, thr_fn, NULL)) {
printf("error when create pthread,%d
", errno);
return 1;
}
char c ;
while ((c = getchar()) != 'q');
printf("Now terminate the thread!
");
flag = 0;
printf("Wait for thread to exit
");
pthread_join(thread, NULL);
printf("Bye
");
return 0;
}
输入q后,需要等线程从sleep中醒来(由挂起状态变为运行状态),即坏情况要等10s,线程才会被join。采用sleep的缺
点:不能及时唤醒线程。
采用pthread_cond_timedwait函数实现的如下:
#include <stdio.h>
#include <sys/time.h>
#include <unistd.h>
#include <pthread.h>
#include <errno.h>
资源评论
weixin_38706747
- 粉丝: 5
- 资源: 962
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功