找回密码
 用户注册

QQ登录

只需一步,快速开始

查看: 3915|回复: 0

关于SLEEP函数

[复制链接]
发表于 2012-2-19 22:23:42 | 显示全部楼层 |阅读模式
以前很喜欢用sleep和usleep函数来做定时器。确实方便啊。但是昨天在公司用这个函数写了个东西,被说这2个函数最好别在多线程里面使用。然后叫我改一个定时器方案。查看了man文档。发现sleep还真有问题。里面就写得有BUG:


BUGS
sleep() may be implemented using SIGALRM; mixing calls to alarm() and sleep() is a bad idea.




       Using longjmp() from a signal handler or modifying the handling of SIGALRM while sleeping will cause undefined results.
说到了用sleep在多线程的不适合。因为是用的信号驱动来实现的。可能要引起不确定的因素。后来去网上找了下其他的方法,这里把方法贴出来。一个在多线程中比较好的实现是利用的pthread库里面的pthread_cond_timewait()函数来实现。下面贴出来代码。都比较基础。
  1. void thread_sleep(int second)
  2. {
  3.      /*  time wait */
  4.     struct timespec outtime;
  5.     pthread_cond_t cond;
  6.     pthread_mutex_t mutex;
  7.     /*  timer init */
  8.     pthread_mutex_init(&mutex, NULL);
  9.     pthread_cond_init(&cond, NULL);
  10.     pthread_mutex_lock(&mutex);
  11.     outtime.tv_sec = time(NULL) + second;  
  12.     outtime.tv_nsec = 0;
  13.     pthread_cond_timedwait(&cond, &mutex, &outtime);
  14.     pthread_mutex_unlock(&mutex);
  15. }
复制代码


作者:yutao52shi 发表于2012-2-19 17:18:08 原文链接

您需要登录后才可以回帖 登录 | 用户注册

本版积分规则

Archiver|手机版|小黑屋|ACE Developer ( 京ICP备06055248号 )

GMT+8, 2024-4-27 11:43 , Processed in 0.010691 second(s), 6 queries , Redis On.

Powered by Discuz! X3.5

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表