有一种方法可以在工作线程之间共享数据,那就是使用 Stackable
<?php
class data extends Stackable{
public function __construct($_name) {
echo __FILE__.'-'.__LINE__.'<br/>'.chr(10);
}
public function run(){
echo __FILE__.'-'.__LINE__.'<br/>'.chr(10);
}
}
class readWorker extends Worker {
public function __construct(&$_data) {
$this->data = $_data;}
public function run(){
while(1){
if($arr=$this->data->shift()){
echo 'Received data:'.print_r($arr,1).chr(10);
}else usleep(50000);
}
}
}
class writeWorker extends Worker {
public function __construct(&$_data) {
$this->data = $_data;}
public function run(){
while(1){
$this->data[] = array(time(),rand());usleep(rand(50000, 1000000));
}
}
}
$data = new data('');
$reader = new readWorker($data);
$writer = new writeWorker($data);
$reader->start();
$writer->start();
?>
你也可以使用 $readWorker[] = $some_data; 然后在 readWorker 中使用 $this->shift() 来与 readWorker 共享数据,但如果你这样做,你不能在 readWorker 中有变量,因为所有变量都将被 shift();