简体   繁体   English

在PHP中,睡眠和睡眠行为在内部表现不同吗?

[英]Do sleep and usleep behave differently internally, in PHP?

I have a socket server listening to a connection for incoming data and writing outgoing data during pauses in input. 我有一个套接字服务器在输入暂停期间监听传入数据的连接并写入传出数据。 Since this is in a loop I am making a sleep call in order to allow other processes to have some CPU time while my process is not expecting input right away. 由于这是一个循环,我正在进行一个sleep调用,以便允许其他进程有一些CPU时间,而我的进程不会立即期望输入。

I know sleep does this, but does usleep also return execution to the OS? 我知道sleep usleep ,但是我们sleep也会将执行返回给操作系统吗? I am suspicious because I know that, traditionally, the sleep syscall only accepts seconds, and a VERY old book I have read about C programming ten years ago said that to "sleep" for shorter intervals involves hacks like making an infinite loop to essentially simulate the sleep call but not cede CPU time to other processes. 我很怀疑,因为我知道,传统上, sleep系统只能接受几秒钟,十年前我读过一本关于C编程的非常古老的书说,为了更短的时间间隔“睡眠”,就像制造一个无限循环来实现模拟sleep调用但不会将CPU时间交给其他进程。 (This book may have been wrong, or may no longer be accurate, I'm just telling you what it said.) (这本书可能错了,或者可能不再准确,我只是告诉你它说了什么。)

I am using Linux, PHP versions 5.6 and 7.1 我使用的是Linux,PHP 5.6和7.1版

thank you 谢谢

It is platform-dependent, but on Linux you can use this simple script to test: 它依赖于平台,但在Linux上,您可以使用这个简单的脚本来测试:

$start = microtime(true);

while(true){
        while(microtime(true) - $start < .9){}
}

//while(true){
//      usleep(900000);
//}

Run it with php test.php & top -d 0.1 the first time to observe what a false sleep looks like, kill the spawned php process after done inspecting top , comment out the first while loop and uncomment the second one, re-run the script and note the CPU usage. 首次使用php test.php & top -d 0.1运行它来观察虚假sleep是什么样的,在完成检查top之后杀死生成的php进程,注释掉第一个while循环并取消注释第二个,重新运行脚本并记下CPU使用情况。

Thanks to Halcyon for giving me the idea to test it myself. 感谢Halcyon给我自己测试它的想法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM