| ... | ... | @@ -0,0 +1,43 @@ |
| 1 | // SPDX-License-Identifier: MIT |
| 2 | // Copyright (c) 2015-2020 Zig Contributors |
| 3 | // This file is part of [zig](https://ziglang.org/), which is MIT licensed. |
| 4 | // The MIT license requires this copyright notice to be included in all copies |
| 5 | // and substantial portions of the software. |
| 6 | |
| 7 | const std = @import("std"); |
| 8 | const builtin = std.builtin; |
| 9 | const testing = std.testing; |
| 10 | |
| 11 | /// Thread-safe, lock-free boolean |
| 12 | pub const Bool = extern struct { |
| 13 | unprotected_value: bool, |
| 14 | |
| 15 | pub const Self = @This(); |
| 16 | |
| 17 | pub fn init(init_val: bool) Self { |
| 18 | return Self{ .unprotected_value = init_val }; |
| 19 | } |
| 20 | |
| 21 | // xchg is only valid rmw operation for a bool |
| 22 | /// Atomically modifies memory and then returns the previous value. |
| 23 | pub fn xchg(self: *Self, operand: bool, comptime ordering: std.builtin.AtomicOrder) bool { |
| 24 | return @atomicRmw(bool, &self.unprotected_value, .Xchg, operand, ordering); |
| 25 | } |
| 26 | |
| 27 | pub fn load(self: *Self, comptime ordering: std.builtin.AtomicOrder) bool { |
| 28 | return @atomicLoad(bool, &self.unprotected_value, ordering); |
| 29 | } |
| 30 | |
| 31 | pub fn store(self: *Self, value: bool, comptime ordering: std.builtin.AtomicOrder) void { |
| 32 | @atomicStore(bool, &self.unprotected_value, value, ordering); |
| 33 | } |
| 34 | }; |
| 35 | |
| 36 | test "std.atomic.Bool" { |
| 37 | var a = Bool.init(false); |
| 38 | testing.expectEqual(false, a.xchg(false, .SeqCst)); |
| 39 | testing.expectEqual(false, a.load(.SeqCst)); |
| 40 | a.store(true, .SeqCst); |
| 41 | testing.expectEqual(true, a.xchg(false, .SeqCst)); |
| 42 | testing.expectEqual(false, a.load(.SeqCst)); |
| 43 | } |