blob: e4126b1ab36253225db46a5c06af4e59c41f3e2b (
plain)
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
|
const std = @import("std");
const WaitGroup = @This();
mutex: std.Thread.Mutex = .{},
counter: usize = 0,
event: std.Thread.ResetEvent,
pub fn init(self: *WaitGroup) !void {
self.* = .{
.mutex = .{},
.counter = 0,
.event = undefined,
};
try self.event.init();
}
pub fn deinit(self: *WaitGroup) void {
self.event.deinit();
self.* = undefined;
}
pub fn start(self: *WaitGroup) void {
self.mutex.lock();
defer self.mutex.unlock();
self.counter += 1;
}
pub fn finish(self: *WaitGroup) void {
self.mutex.lock();
defer self.mutex.unlock();
self.counter -= 1;
if (self.counter == 0) {
self.event.set();
}
}
pub fn wait(self: *WaitGroup) void {
while (true) {
self.mutex.lock();
if (self.counter == 0) {
self.mutex.unlock();
return;
}
self.mutex.unlock();
self.event.wait();
}
}
pub fn reset(self: *WaitGroup) void {
self.event.reset();
}
|