Linux操作系统 sleep(0)、sleep(1)和sleep(-1)的区别,他们各有什么作用

sleep(0)、sleep(1)和sleep(-1)的区别,他们各有什么作用?

  • freeboy1015

    2 票

  • freeboy1015
    2598

sleep(0)、sleep(1)、sleep(-1)的区别,他们各有什么作用?对于Sleep(1)所产生的效果,在不同的系统上会/有不同的表现吗?sleep(-1)的作用是什么?

freeboy1015
编辑于 2012-12-14
评论 ( 4) •  分享 •  链接 •  2012-12-13 
  • 0
    什么地方用的sleep()? –  runer  2012-12-13
  • 0
    man sleep –  斑驳-neo  2012-12-13
  • 0
    @runer linux,多线程 –  freeboy1015  2012-12-14
  • 0
    还没用过sleep(-1) –  274131487  2012-12-18
3个答案
票 数 
  • ajaxhe

    1 票

  • 2886
  • 最佳答案

linux中sleep的函数参数是unsigned int,如下:

        
        
        
        
  1. #include <unistd.h>
  2. unsigned int sleep(unsigned int seconds);

参考链接:sleep(3) - Linux man page

sleep(-1)调用导致隐形的类型转换,-1就转化成0xffffffff,也就是32位无符号整形的最大值

sleep(0)的结果与系统实现有关, glibc针对Linux的实现, sleep(0)不会做任何系统调用而直接返回。(glibc2.9中sleep源码)

        
        
        
        
  1. /* We are going to use the `nanosleep' syscall of the kernel.  
  2.    But the kernel does not implement the stupid SysV SIGCHLD
  3.    vs. SIG_IGN behaviour for this syscall.  Therefore we have
  4.    to emulate it here.  */
  5. unsigned int
  6. __sleep (unsigned int seconds)
  7. {
  8.   const unsigned int max
  9.     = (unsigned int) (((unsigned long int) (~((time_t) 0))) >> 1);
  10.   struct timespec ts;
  11.   sigset_t set, oset;
  12.   /* This is not necessary but some buggy programs depend on this.  */
  13.   if (__builtin_expect (seconds == 0, 0))
  14.     {
  15. #ifdef CANCELLATION_P
  16.       CANCELLATION_P (THREAD_SELF);  //相当于 pthread_testcancel();0
  17. #endif
  18.       return 0;
  19.     }
  20. ... ...
  21. }

只有sleep(1)时, 才会调用到nanosleep

参考链接:
关于sleep(0)
sched_yield vs. sleep(0)

freeboy1015
freeboy1015
2598
编辑于  2012-12-17
评论 ( 1) •  链接 • 2012-12-17
  • 0
    我看的一段代码中sleep(-1)的功能好像是“阻止程序退出”。 –  freeboy1015  2012-12-17
  • 双人份

    0 票

  • 双人份
    3

sleep(-1)就是sleep(UINT_MAX)

评论 ( 0) •  链接 • 2012-12-13
  • SecureCore

    0 票

  • SecureCore
    1

sleep(0)是让出CPU
linux下是usleep吧

评论 ( 0) •  链接 • 2012-12-17

你可能感兴趣的:(Linux操作系统 sleep(0)、sleep(1)和sleep(-1)的区别,他们各有什么作用)