最近版本的pthreads支持闭包作为成员,使得代码非常简单:
<?php
class Background extends Thread {
public function __construct(callable $call, array $args = []) {
$this->call = $call;
$this->args = $args;
}
public function run() {
call_user_func_array($this->call, $this->args);
}
protected $call;
protected $args;
}
$background = new Background(function($greeting){
printf("%s\n", $greeting);
}, ["Hello World"]);
$background->start();
$background->join();
function named($greeting) {
printf("%s\n", $greeting);
}
$background = new Background("named", ["Goodbye World"]);
$background->start();
$background->join();
?>
然而,这是很糟糕的,很难想象有任何函数是如此饥饿以至于需要一个自己的线程。
你已经走上了正确的道路,考虑重用上下文并创建一个工作线程,pthreads已经内置了所有这些功能。
更合理的使用内置类的代码看起来更像:
<?php
class Background extends Threaded {
public function __construct(callable $call, array $args = []) {
$this->call = $call;
$this->args = $args;
}
public function run() {
call_user_func_array($this->call, $this->args);
}
protected $call;
protected $args;
}
$pool = new Pool(4);
$pool->submit(new Background(function($greeting){
printf("%s\n", $greeting);
}, ["Hello World"]));
$pool->shutdown();
?>
但这仍然无法处理返回值。我假设您想要检索使用 Pool
进行的调用的结果,那么代码看起来更像:
<?php
class Background extends Threaded {
public function __construct(callable $call, array $args = []) {
$this->call = $call;
$this->args = $args;
}
public function run() {
$this->synchronized(function(){
$this->result = call_user_func_array
($this->call, $this->args);
$this->notify();
});
}
public function getResult() {
return $this->synchronized(function(){
while (!isset($this->result))
$this->wait();
return $this->result;
});
}
protected $call;
protected $args;
protected $result;
}
$pool = new Pool(4);
$call = new Background(function($greeting){
return sprintf("%s\n", $greeting);
}, ["Hello World"]);
$pool->submit($call);
echo $call->getResult();
$pool->shutdown();
?>
正如您所看到的,调用Background::getResult
将导致调用上下文等待结果可用,这可能是可取的,也可能不是,但可以作为一个很好的例子。