Advertisement
Guest User

php pthreads pool collect callback (attempt)

a guest
Feb 9th, 2015
339
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.01 KB | None | 0 0
  1. <?php
  2.  
  3. class Task extends Thread {
  4.     public $n;
  5.     public $result;
  6.     public $done = false;
  7.  
  8.     public function __construct ($n) {
  9.         $this->n = $n;
  10.     }
  11.  
  12.     public function run () {
  13.         usleep(mt_rand(1,10) * 100000);
  14.         $this->result = $this->n * $this->n;
  15.         $this->done = true;
  16.     }
  17. }
  18.  
  19. class MyPool {
  20.     private $tasks = [];
  21.  
  22.     public function submit (\Task $task) {
  23.         array_push($this->tasks, $task);
  24.         $task->start();
  25.     }
  26.  
  27.     public function collect ($callback) {
  28.         while (true) {
  29.             $all_done = true;
  30.  
  31.             foreach ($this->tasks as $i => &$task) {
  32.                 if ($task->done) {
  33.                     call_user_func($callback, $task);
  34.                     unset($this->tasks[$i]);
  35.                     unset($task);
  36.  
  37.                 } else {
  38.                     $all_done = false;
  39.                 }
  40.             }
  41.  
  42.             if ($all_done) {
  43.                 break;
  44.             }
  45.         }
  46.     }
  47.  
  48. }
  49.  
  50.  
  51. $items = range(0, 5);
  52. $pool = new MyPool;
  53.  
  54. foreach ($items as $n => $v) {
  55.     $pool->submit(new Task($n));
  56. }
  57.  
  58. print_r($items);
  59.  
  60. $pool->collect(function (Task $task) use (&$items) {
  61.     $items[$task->n] = $task->result;
  62. });
  63.  
  64. print_r($items);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement