演示 Pool/Worker 机制用法,以及一些技巧和提示的示例类 ;)
<?php
class Config extends Threaded{ protected $val=0, $val2=0;
protected function inc(){++$this->val;} public function inc2(){++$this->val2;} }
class WorkerClass extends Worker{
protected static $worker_id_next = -1;
protected $worker_id;
protected $config;
public function __construct($config){
$this->worker_id = ++static::$worker_id_next; $this->config = $config;
}
public function run(){
global $config;
$config = $this->config; global $worker_id;
$worker_id = $this->worker_id;
echo "working context {$worker_id} is created!\n";
}
protected function say_config(){ global $config; $config->synchronized(function() use (&$config){ var_dump($config);
});
}
}
class Task extends Stackable{ protected $set;
public function __construct($set){
$this->set = $set;
}
public function run(){
global $worker_id;
echo "task is running in {$worker_id}!\n";
usleep(mt_rand(1,100)*100);
$config = $this->getConfig();
$val = $config->arr->shift();
$config->arr[] = $this->set;
for ($i = 0 ; $i < 1000; ++$i){
$config->inc();
$config->inc2();
}
}
public function getConfig(){
global $config; return $config;
}
}
$config = new Config;
$config->arr = new \Threaded();
$config->arr->merge(array(1,2,3,4,5,6));
class PoolClass extends Pool{
public function worker_list(){
if ($this->workers !== null)
return array_keys($this->workers);
return null;
}
}
$pool = new PoolClass(3, 'WorkerClass', [$config] );
$pool->worker_list();
$spammed_id = -1;
for ($i = 1; $i <= 100; ++$i){ if ($spammed_id == -1 && ($x = $pool->worker_list())!= null && @$x[2]){
$spammed_id = $x[2];
echo "spamming worker {$spammed_id} with lots of tasks from now on\n";
}
if ($spammed_id != -1 && ($i % 5) == 0) $pool->submitTo($spammed_id,new Task(10*$i));
else
$pool->submit(new Task(10*$i));
}
$pool->shutdown();
var_dump($config); ?>