关于SLEEP函数

以前很喜欢用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()函数来实现。下面贴出来代码。都比较基础。

void thread_sleep(int second)
{
     /*  time wait */
    struct timespec outtime;
    pthread_cond_t cond;
    pthread_mutex_t mutex;

    /*  timer init */
    pthread_mutex_init(&mutex, NULL); 
    pthread_cond_init(&cond, NULL);

    pthread_mutex_lock(&mutex);
    outtime.tv_sec = time(NULL) + second;  
    outtime.tv_nsec = 0;
    pthread_cond_timedwait(&cond, &mutex, &outtime);
    pthread_mutex_unlock(&mutex);
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值