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