Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- class Task extends Thread {
- public $n;
- public $result;
- public $done = false;
- public function __construct ($n) {
- $this->n = $n;
- }
- public function run () {
- usleep(mt_rand(1,10) * 100000);
- $this->result = $this->n * $this->n;
- $this->done = true;
- }
- }
- class MyPool {
- private $tasks = [];
- public function submit (\Task $task) {
- array_push($this->tasks, $task);
- $task->start();
- }
- public function collect ($callback) {
- while (true) {
- $all_done = true;
- foreach ($this->tasks as $i => &$task) {
- if ($task->done) {
- call_user_func($callback, $task);
- unset($this->tasks[$i]);
- unset($task);
- } else {
- $all_done = false;
- }
- }
- if ($all_done) {
- break;
- }
- }
- }
- }
- $items = range(0, 5);
- $pool = new MyPool;
- foreach ($items as $n => $v) {
- $pool->submit(new Task($n));
- }
- print_r($items);
- $pool->collect(function (Task $task) use (&$items) {
- $items[$task->n] = $task->result;
- });
- print_r($items);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement