WaitGroup.php 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. <?php
  2. namespace EasySwoole\Component;
  3. use Swoole\Coroutine\Channel;
  4. class WaitGroup
  5. {
  6. private $count = 0;
  7. /** @var Channel */
  8. private $channel;
  9. private $success = 0;
  10. private $size;
  11. public function __construct(int $size = 128)
  12. {
  13. $this->size = $size;
  14. $this->reset();
  15. }
  16. public function add()
  17. {
  18. $this->count++;
  19. }
  20. function successNum():int
  21. {
  22. return $this->success;
  23. }
  24. public function done()
  25. {
  26. $this->channel->push(1);
  27. }
  28. public function wait(?float $timeout = 15)
  29. {
  30. if($timeout <= 0){
  31. $timeout = PHP_INT_MAX;
  32. }
  33. $this->success = 0;
  34. $left = $timeout;
  35. while(($this->count > 0) && ($left > 0))
  36. {
  37. $start = round(microtime(true),3);
  38. if($this->channel->pop($left) === 1)
  39. {
  40. $this->count--;
  41. $this->success++;
  42. }
  43. $left = $left - (round(microtime(true),3) - $start);
  44. }
  45. }
  46. function reset()
  47. {
  48. $this->close();
  49. $this->count = 0;
  50. $this->success = 0;
  51. $this->channel = new Channel($this->size);
  52. }
  53. function close()
  54. {
  55. if($this->channel){
  56. $this->channel->close();
  57. $this->channel = null;
  58. }
  59. }
  60. function __destruct()
  61. {
  62. $this->close();
  63. }
  64. }