我正在尝试在 PHP 中创建某种异步超时。
我使用 PECL 扩展 pthreads 来实现多线程。
异步超时工作正常,但参考却不然。
我使用 PHP 5.5.8 进行此测试。
class ParentClass {
public $test;
public function __construct(){
}
public function test() {
echo $this->test;
}
}
class Timeout extends Thread {
private $seconds;
private $parent;
public function __construct($seconds, &$parent){
$this->seconds = $seconds;
$this->parent = $parent;
}
public function run(){
sleep($this->seconds);
$this->parent->test();
}
}
$parent = new ParentClass();
$parent->test = "Hello.\n";
$timeout = new Timeout(2, $parent);
$timeout->start();
$parent->test = "Bye.\n";
$parent->test();
期待
Bye.
Bye.
Getting
Bye.
Hello.
有人可以告诉我我做错了什么吗?
对于多线程应用程序,不应使用 sleep(),PHP 调用的底层实现旨在导致进程休眠,而不是进程内的线程休眠。里程会有所不同,某些实现很可能会导致线程休眠,但您不能也不应该依赖它。
usleep 更适合多线程,因为它旨在使线程休眠,而不是进程休眠,但是,它也会使线程处于非接收状态。
pthreads 内置了专为多线程设计的适当同步方法,使线程在等待某些事情发生时处于接收状态。
引用不起作用,也不必起作用,如果您希望在多个上下文之间传递对象进行操作,则该对象应该来自 pthread。
<?php
define("SECOND", 1000000);
class ParentClass extends Stackable {
public function test() {
echo $this->test;
}
public function run(){}
public $test;
}
class Timeout extends Thread {
public function __construct($seconds, $parent){
$this->seconds = $seconds;
$this->parent = $parent;
}
public function run(){
$this->synchronized(function(){
$this->wait(
SECOND * $this->seconds);
});
$this->parent->test();
}
private $seconds;
private $parent;
}
$parent = new ParentClass();
$parent->test = "Hello.\n";
$timeout = new Timeout(2, $parent);
$timeout->start();
$parent->test = "Bye.\n";
$parent->test();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)