<?php
class test extends Thread {
public $name = '';
public $runing = false;
public function __construct($name) {
$this->name = $name;
$this->runing = true;
}
public function run() {
$n = 0;
while ($this->runing) {
printf("name: %s %s\n",$this->name, $n);
$n++;
sleep(1);
}
}
}
$pool[] = new test('a');
$pool[] = new test('b');
$pool[] = new test('c');
foreach ($pool as $w) {
$w->start();
}
<?php
class ExampleWork extends Stackable {
public function __construct($data) {
$this->local = $data;
}
public function run() {
//print_r($this->local);echo "\r\n";
echo '------------------- '. $this->local . " -----------------\r\n";
sleep(1);
}
}
class ExampleWorker extends Worker {
public function __construct($name) {
$this->name = $name;
$this->data = array();
}
public function run(){
$this->name = sprintf("(%lu)", $this->getThreadId());
}
}
/* Dead simple pthreads pool */
class Pool {
/* to hold worker threads */
public $workers;
/* to hold exit statuses */
public $status;
/* prepare $size workers */
public function __construct($size = 10) {
$this->size = $size;
}
/* submit Stackable to Worker */
public function submit(Stackable $stackable) {
if (count($this->workers)<$this->size) {
$id = count($this->workers);
$this->workers[$id] = new ExampleWorker(sprintf("Worker [%d]", $id));
$this->workers[$id]->start(PTHREADS_INHERIT_NONE);
if ($this->workers[$id]->stack($stackable)) {
return $stackable;
} else trigger_error(sprintf("failed to push Stackable onto %s", $this->workers[$id]->getName()), E_USER_WARNING);
}else{
for ($i=0;$i<count($this->workers);$i++){
if( ! $this->workers[$i]->isWorking()){
$this->workers[$i]->stack($stackable);
return $stackable;
}
}
}
return false;
}
public function status(){
for ($i=0;$i<count($this->workers);$i++){
printf("(%s:%s)\r\n",$i, $this->workers[$i]->isWorking());
}
printf("\r\n");
}
/* Shutdown the pool of threads cleanly, retaining exit status locally */
public function shutdown() {
foreach($this->workers as $worker) {
$this->status[$worker->getThreadId()]=$worker->shutdown();
}
}
}
/* Create a pool of ten threads */
$pool = new Pool(100);
/* Create and submit an array of Stackables */
$work = array();
for ($target = 0; $target < 1000; $target++){
$work[$target]=$pool->submit(new ExampleWork($target));
if($work[$target] == false){
$target--;
sleep(1);
continue;
}
for ($i=0;$i<count($work);$i++){
if($work[$i]->isRunning()){
printf("cell: %s, status: %s\r\n",$i, $work[$i]->isRunning());
}
}
printf("\r\n");
}
$pool->shutdown();