From 32fd637e57c3b4391b3f2f4499c803e3d4e8f615 Mon Sep 17 00:00:00 2001 From: Andrew Kelley Date: Fri, 18 Dec 2020 16:14:46 -0700 Subject: [PATCH] stage2: replace WaitGroup with a trivially auditable one --- src/WaitGroup.zig | 30 +++++++++++++++++++++--------- 1 file changed, 21 insertions(+), 9 deletions(-) diff --git a/src/WaitGroup.zig b/src/WaitGroup.zig index 295dfd39dc805e38cc14041987b1ff8490107dc6..c33d084c28ce60ea571c963f5f144ed69967d584 100644 --- a/src/WaitGroup.zig +++ b/src/WaitGroup.zig @@ -1,22 +1,34 @@ const std = @import("std"); const WaitGroup = @This(); +lock: std.Mutex = .{}, counter: usize = 0, -event: ?*std.AutoResetEvent = null, +event: std.AutoResetEvent = .{}, pub fn start(self: *WaitGroup) void { - _ = @atomicRmw(usize, &self.counter, .Add, 1, .SeqCst); + const held = self.lock.acquire(); + defer held.release(); + + self.counter += 1; } pub fn stop(self: *WaitGroup) void { - if (@atomicRmw(usize, &self.counter, .Sub, 1, .SeqCst) == 1) - if (@atomicRmw(?*std.AutoResetEvent, &self.event, .Xchg, null, .SeqCst)) |event| - event.set(); + const held = self.lock.acquire(); + defer held.release(); + + self.counter -= 1; + if (self.counter == 0) + self.event.set(); } pub fn wait(self: *WaitGroup) void { - var event = std.AutoResetEvent{}; - @atomicStore(?*std.AutoResetEvent, &self.event, &event, .SeqCst); - if (@atomicLoad(usize, &self.counter, .SeqCst) != 0) - event.wait(); + { + const held = self.lock.acquire(); + defer held.release(); + + if (self.counter == 0) + return; + } + + self.event.wait(); } -- 2.54.0