最新版本的pthreads支持闭包作为成员,使代码非常简单:
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已经内置了所有这些.
使用内置类的更合理的代码看起来更像:
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进行的调用的结果,在这种情况下代码看起来更像:
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的调用将导致调用上下文一直等到结果可用,这可能是也可能不是,但这是一个很好的例子.