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?
Advertisement
Answer
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 */ PHP_FUNCTION(sleep) { zend_long num; ZEND_PARSE_PARAMETERS_START(1, 1) Z_PARAM_LONG(num) ZEND_PARSE_PARAMETERS_END(); if (num < 0) { zend_argument_value_error(1, "must be greater than or equal to 0"); RETURN_THROWS(); } 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.