mirror of
https://github.com/ziglang/zig.git
synced 2025-12-06 06:13:07 +00:00
* move std.atomic.Atomic to std.atomic.Value * fix incorrect argument order passed to testing.expectEqual * make the functions be a thin wrapper over the atomic builtins and stick to the naming conventions. * remove pointless functions loadUnchecked and storeUnchecked. Instead, name the field `raw` instead of `value` (which is redundant with the type name). * simplify the tests by not passing every possible combination. Many cases were iterating over every possible combinations but then not even using the for loop element value! * remove the redundant compile errors which are already implemented by the language itself. * remove dead x86 inline assembly. this should be implemented in the language if at all.
46 lines
1.1 KiB
Zig
46 lines
1.1 KiB
Zig
const std = @import("std");
|
|
const assert = std.debug.assert;
|
|
const WaitGroup = @This();
|
|
|
|
const is_waiting: usize = 1 << 0;
|
|
const one_pending: usize = 1 << 1;
|
|
|
|
state: std.atomic.Value(usize) = std.atomic.Value(usize).init(0),
|
|
event: std.Thread.ResetEvent = .{},
|
|
|
|
pub fn start(self: *WaitGroup) void {
|
|
const state = self.state.fetchAdd(one_pending, .Monotonic);
|
|
assert((state / one_pending) < (std.math.maxInt(usize) / one_pending));
|
|
}
|
|
|
|
pub fn finish(self: *WaitGroup) void {
|
|
const state = self.state.fetchSub(one_pending, .Release);
|
|
assert((state / one_pending) > 0);
|
|
|
|
if (state == (one_pending | is_waiting)) {
|
|
self.state.fence(.Acquire);
|
|
self.event.set();
|
|
}
|
|
}
|
|
|
|
pub fn wait(self: *WaitGroup) void {
|
|
const state = self.state.fetchAdd(is_waiting, .Acquire);
|
|
assert(state & is_waiting == 0);
|
|
|
|
if ((state / one_pending) > 0) {
|
|
self.event.wait();
|
|
}
|
|
}
|
|
|
|
pub fn reset(self: *WaitGroup) void {
|
|
self.state.store(0, .Monotonic);
|
|
self.event.reset();
|
|
}
|
|
|
|
pub fn isDone(wg: *WaitGroup) bool {
|
|
const state = wg.state.load(.Acquire);
|
|
assert(state & is_waiting == 0);
|
|
|
|
return (state / one_pending) == 0;
|
|
}
|