Skip to content

Commit b10ed9e

Browse files
authored
Add AwaitGroup!
1 parent c06596e commit b10ed9e

File tree

1 file changed

+112
-0
lines changed

1 file changed

+112
-0
lines changed

src/vennv/vapm/AwaitGroup.php

Lines changed: 112 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,112 @@
1+
<?php
2+
3+
/**
4+
* Vapm - A library support for PHP about Async, Promise, Coroutine, Thread, GreenThread
5+
* and other non-blocking methods. The library also includes some Javascript packages
6+
* such as Express. The method is based on Fibers & Generator & Processes, requires
7+
* you to have php version from >= 8.1
8+
*
9+
* Copyright (C) 2023 VennDev
10+
*
11+
* This program is free software; you can redistribute it and/or modify
12+
* it under the terms of the GNU General Public License as published by
13+
* the Free Software Foundation; either version 2 of the License, or
14+
* (at your option) any later version.
15+
*
16+
* This program is distributed in the hope that it will be useful,
17+
* but WITHOUT ANY WARRANTY; without even the implied warranty of
18+
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19+
* GNU General Public License for more details.
20+
*/
21+
22+
declare(strict_types=1);
23+
24+
namespace vennv\vapm;
25+
26+
use Generator;
27+
28+
interface AwaitGroupInterface
29+
{
30+
31+
/**
32+
* @param int $count
33+
* @return void
34+
*
35+
* This function is used to add the count to the group
36+
*/
37+
public function add(int $count): void;
38+
39+
/**
40+
* @return Generator
41+
*
42+
* This function is used to decrement the count
43+
*/
44+
public function done(): Generator;
45+
46+
/**
47+
* @return bool
48+
*
49+
* This function is used to check if the count is zero
50+
*/
51+
public function isDone(): bool;
52+
53+
/**
54+
* @return int
55+
*
56+
* This function is used to get the count
57+
*/
58+
public function getCount(): int;
59+
60+
/**
61+
* @return void
62+
*
63+
* This function is used to wait for the count to be zero
64+
*/
65+
public function reset(): void;
66+
67+
}
68+
69+
final class AwaitGroup implements AwaitGroupInterface
70+
{
71+
72+
private int $count = 0;
73+
74+
public function add(int $count): void
75+
{
76+
$this->count += $count;
77+
}
78+
79+
public function done(): Generator
80+
{
81+
$this->count--;
82+
yield;
83+
}
84+
85+
public function isDone(): bool
86+
{
87+
return $this->count === 0;
88+
}
89+
90+
public function getCount(): int
91+
{
92+
return $this->count;
93+
}
94+
95+
public function reset(): void
96+
{
97+
$this->count = 0;
98+
}
99+
100+
public function wait(): void
101+
{
102+
while ($this->count > 0) {
103+
// Wait for the count to be zero
104+
}
105+
}
106+
107+
public function __destruct()
108+
{
109+
$this->reset();
110+
}
111+
112+
}

0 commit comments

Comments
 (0)