-
Notifications
You must be signed in to change notification settings - Fork 25
/
Copy pathWaitGroup.php
90 lines (76 loc) · 1.75 KB
/
WaitGroup.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
<?php
namespace EasySwoole\Component;
use Swoole\Coroutine;
use Swoole\Coroutine\Channel;
class WaitGroup
{
private $count = 0;
/** @var Channel */
private $channel;
private $success = 0;
private $size;
public function __construct(int $size = 128)
{
$this->size = $size;
$this->reset();
}
public function add(?callable $func = null)
{
$this->count++;
if($func){
Coroutine::create(function ()use($func){
try{
call_user_func($func);
}catch (\Throwable $throwable){
throw $throwable;
}finally {
$this->done();
}
});
}
}
function successNum():int
{
return $this->success;
}
public function done()
{
$this->channel->push(1);
}
public function wait(?float $timeout = 15)
{
if($timeout <= 0){
$timeout = PHP_INT_MAX;
}
$this->success = 0;
$left = $timeout;
while(($this->count > 0) && ($left > 0))
{
$start = round(microtime(true),3);
if($this->channel->pop($left) === 1)
{
$this->count--;
$this->success++;
}
$left = $left - (round(microtime(true),3) - $start);
}
}
function reset()
{
$this->close();
$this->count = 0;
$this->success = 0;
$this->channel = new Channel($this->size);
}
function close()
{
if($this->channel){
$this->channel->close();
$this->channel = null;
}
}
function __destruct()
{
$this->close();
}
}