In PHP, does sleep(0) still yield or is it ignored?


In PHP, if you use sleep(0);, will it be ignored (either by PHP or by the OS), or will it still yield execution to another thread temporarily? Does it incur any overhead? Does it depend on the version of PHP or the OS?


I decided to look into this again since someone upvoted the question.

As seen in basic_functions.c, it calls a function named php_sleep:

/* {{{ Delay for a given number of seconds */
    zend_long num;


    if (num < 0) {
        zend_argument_value_error(1, "must be greater than or equal to 0");

    RETURN_LONG(php_sleep((unsigned int)num));  // <----- php_sleep
/* }}} */

php_sleep is defined in php.h as follows (unless PHP is running on win32):

#ifndef PHP_WIN32
#define php_sleep sleep
extern char **environ;
#endif  /* ifndef PHP_WIN32 */

So it’s using the standard sleep which is being included with unistd.h elsewhere in the file, whose implementation probably depends on which platform you’re using and which flavor of libc and all that. I’ve seen posts on the internet claiming that old versions of the function would explicitly check if the argument was 0 and early exit, and others saying that sleep(0) is one way of cooperatively yielding your thread to the OS for the shortest time possible.

So after all this time, unsatisfyingly, the answer is: it depends.

Answered By – philraj

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published