在libc的info描述如下:(info sleep)
On some systems, sleep' can do strange things if your program uses
SIGALRM’ explicitly. Even if
SIGALRM' signals are being ignored or
sleep’ is called,
blocked whensleep' might return prematurely on
SIGALRM’ signal.
delivery of a
On the GNU system, it is safe to use sleep' and
SIGALRM’ in the
same program, because sleep' does not work by means of
SIGALRM’.
大意就是各个系统中,sleep不统一,对应SIGALRM处理不尽相同.
参考:http://www.cnblogs.com/qingxia/archive/2012/08/30/2663791.html
这篇文章中提到了利用sleep不能及时唤醒的说法,个人觉得只是很小一部分的原因。
最重要的sleep各平台(类UNIX系统)兼容性不是很好。
利用pthread_cond_timedwait就可以实现出 GNU 中类似的sleep:”does not work by means of SIGALRM”
代码:
sleep.c
#include <pthread.h>
#include <unistd.h>
#include <time.h>
#include <sys/time.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
void pthread_sleep( unsigned int ms )
{
struct timespec deadline;
struct timeval now;
gettimeofday(&now,NULL);
time_t seconds = ms/1000;
long nanoseconds = (ms - seconds * 1000) * 1000000;
deadline.tv_sec = now.tv_sec + seconds;
deadline.tv_nsec = now.tv_usec * 1000 + nanoseconds;
if( deadline.tv_nsec >= 1000000000L )
{
deadline.tv_nsec -= 1000000000L;
deadline.tv_sec++;
}
pthread_mutex_lock(&mutex);
pthread_cond_timedwait(&cond,&mutex,&deadline);
pthread_mutex_unlock(&mutex);
}
int main()
{
pthread_sleep( 12345 );
return 0;
}
gcc sleep.c -lpthread -o test_sleep
如果还要兼容WIN,只需要用宏隔开使用Win中的Sleep就Okay。