master
 1const std = @import("std.zig");
 2const builtin = @import("builtin");
 3const testing = std.testing;
 4
 5pub fn once(comptime f: fn () void) Once(f) {
 6    return Once(f){};
 7}
 8
 9/// An object that executes the function `f` just once.
10/// It is undefined behavior if `f` re-enters the same Once instance.
11pub fn Once(comptime f: fn () void) type {
12    return struct {
13        done: bool = false,
14        mutex: std.Thread.Mutex = std.Thread.Mutex{},
15
16        /// Call the function `f`.
17        /// If `call` is invoked multiple times `f` will be executed only the
18        /// first time.
19        /// The invocations are thread-safe.
20        pub fn call(self: *@This()) void {
21            if (@atomicLoad(bool, &self.done, .acquire))
22                return;
23
24            return self.callSlow();
25        }
26
27        fn callSlow(self: *@This()) void {
28            @branchHint(.cold);
29
30            self.mutex.lock();
31            defer self.mutex.unlock();
32
33            // The first thread to acquire the mutex gets to run the initializer
34            if (!self.done) {
35                f();
36                @atomicStore(bool, &self.done, true, .release);
37            }
38        }
39    };
40}
41
42var global_number: i32 = 0;
43var global_once = once(incr);
44
45fn incr() void {
46    global_number += 1;
47}
48
49test "Once executes its function just once" {
50    if (builtin.single_threaded) {
51        global_once.call();
52        global_once.call();
53    } else {
54        var threads: [10]std.Thread = undefined;
55        var thread_count: usize = 0;
56        defer for (threads[0..thread_count]) |handle| handle.join();
57
58        for (&threads) |*handle| {
59            handle.* = try std.Thread.spawn(.{}, struct {
60                fn thread_fn(x: u8) void {
61                    _ = x;
62                    global_once.call();
63                    if (global_number != 1) @panic("memory ordering bug");
64                }
65            }.thread_fn, .{0});
66            thread_count += 1;
67        }
68    }
69
70    try testing.expectEqual(@as(i32, 1), global_number);
71}