FixedPool.php 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: Jenner
  5. * Date: 2015/11/2
  6. * Time: 17:45
  7. */
  8. namespace Jenner\SimpleFork;
  9. /**
  10. * fixed pool
  11. *
  12. * @package Jenner\SimpleFork
  13. */
  14. class FixedPool extends AbstractPool
  15. {
  16. /**
  17. * @var int max process count
  18. */
  19. protected $max;
  20. /**
  21. * @param int $max
  22. */
  23. public function __construct($max = 4)
  24. {
  25. $this->max = $max;
  26. }
  27. public function execute(Process $process)
  28. {
  29. Utils::checkOverwriteRunMethod(get_class($process));
  30. if ($this->aliveCount() < $this->max && !$process->isStarted()) {
  31. $process->start();
  32. }
  33. array_push($this->processes, $process);
  34. }
  35. /**
  36. * wait for all process done
  37. *
  38. * @param bool $block block the master process
  39. * to keep the sub process count all the time
  40. * @param int $interval check time interval
  41. */
  42. public function wait($block = false, $interval = 100)
  43. {
  44. do {
  45. if ($this->isFinished()) {
  46. return;
  47. }
  48. parent::wait(false);
  49. if ($this->aliveCount() < $this->max) {
  50. foreach ($this->processes as $process) {
  51. if ($process->isStarted()) continue;
  52. $process->start();
  53. if ($this->aliveCount() >= $this->max) break;
  54. }
  55. }
  56. $block ? usleep($interval) : null;
  57. } while ($block);
  58. }
  59. }