Linux多线程编程,替代sleep的几种方式

发表于:2012-8-29 10:25

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:horstlinux    来源:51Testing软件测试网采编

  我只想要进程的某个线程休眠一段时间的,可是用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("******\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的缺点:不能及时唤醒线程。

21/212>
《2023软件测试行业现状调查报告》独家发布~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号