authorgravatar for quae@daurnimator.comdaurnimator <quae@daurnimator.com> 2020-11-19 00:58:13+11:00
committergravatar for quae@daurnimator.comdaurnimator <quae@daurnimator.com> 2020-11-19 00:58:13+11:00
log767dd772c091f072f4b446365e6053021fa67c26
tree2479f21dba826d8462f2a4760344d18afb914305
parentd89d6374bed73683fa92d3c409016fb3f260a7c1
signaturelock-open Commit is signed but in an unrecognized format.

std: add std.atomic.Bool


3 files changed, 46 insertions(+), 0 deletions(-)

CMakeLists.txt+1
......@@ -318,6 +318,7 @@ set(ZIG_STAGE2_SOURCES
318318 "${CMAKE_SOURCE_DIR}/lib/std/array_list.zig"
319319 "${CMAKE_SOURCE_DIR}/lib/std/ascii.zig"
320320 "${CMAKE_SOURCE_DIR}/lib/std/atomic.zig"
321 "${CMAKE_SOURCE_DIR}/lib/std/atomic/bool.zig"
321322 "${CMAKE_SOURCE_DIR}/lib/std/atomic/int.zig"
322323 "${CMAKE_SOURCE_DIR}/lib/std/atomic/queue.zig"
323324 "${CMAKE_SOURCE_DIR}/lib/std/atomic/stack.zig"
lib/std/atomic.zig+2
......@@ -5,10 +5,12 @@
55// and substantial portions of the software.
66pub const Stack = @import("atomic/stack.zig").Stack;
77pub const Queue = @import("atomic/queue.zig").Queue;
8pub const Bool = @import("atomic/bool.zig").Bool;
89pub const Int = @import("atomic/int.zig").Int;
910
1011test "std.atomic" {
1112 _ = @import("atomic/stack.zig");
1213 _ = @import("atomic/queue.zig");
14 _ = @import("atomic/bool.zig");
1315 _ = @import("atomic/int.zig");
1416}
lib/std/atomic/bool.zig created+43
......@@ -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
7const std = @import("std");
8const builtin = std.builtin;
9const testing = std.testing;
10
11/// Thread-safe, lock-free boolean
12pub 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
36test "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}