2020-04-18 12:26:12 +01:00
|
|
|
const std = @import("std.zig");
|
2021-10-05 07:47:27 +01:00
|
|
|
const builtin = @import("builtin");
|
2020-04-18 12:26:12 +01:00
|
|
|
const testing = std.testing;
|
|
|
|
|
|
|
|
pub fn once(comptime f: fn () void) Once(f) {
|
|
|
|
return Once(f){};
|
|
|
|
}
|
|
|
|
|
|
|
|
/// An object that executes the function `f` just once.
|
|
|
|
pub fn Once(comptime f: fn () void) type {
|
|
|
|
return struct {
|
|
|
|
done: bool = false,
|
2021-01-15 03:41:37 +00:00
|
|
|
mutex: std.Thread.Mutex = std.Thread.Mutex{},
|
2020-04-18 12:26:12 +01:00
|
|
|
|
|
|
|
/// Call the function `f`.
|
|
|
|
/// If `call` is invoked multiple times `f` will be executed only the
|
|
|
|
/// first time.
|
|
|
|
/// The invocations are thread-safe.
|
|
|
|
pub fn call(self: *@This()) void {
|
|
|
|
if (@atomicLoad(bool, &self.done, .Acquire))
|
|
|
|
return;
|
|
|
|
|
|
|
|
return self.callSlow();
|
|
|
|
}
|
|
|
|
|
|
|
|
fn callSlow(self: *@This()) void {
|
|
|
|
@setCold(true);
|
|
|
|
|
2021-11-10 01:27:12 +00:00
|
|
|
self.mutex.lock();
|
|
|
|
defer self.mutex.unlock();
|
2020-04-18 12:26:12 +01:00
|
|
|
|
|
|
|
// The first thread to acquire the mutex gets to run the initializer
|
|
|
|
if (!self.done) {
|
|
|
|
f();
|
|
|
|
@atomicStore(bool, &self.done, true, .Release);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
var global_number: i32 = 0;
|
|
|
|
var global_once = once(incr);
|
|
|
|
|
|
|
|
fn incr() void {
|
|
|
|
global_number += 1;
|
|
|
|
}
|
|
|
|
|
|
|
|
test "Once executes its function just once" {
|
|
|
|
if (builtin.single_threaded) {
|
|
|
|
global_once.call();
|
|
|
|
global_once.call();
|
|
|
|
} else {
|
2021-06-20 03:31:43 +01:00
|
|
|
var threads: [10]std.Thread = undefined;
|
|
|
|
defer for (threads) |handle| handle.join();
|
2020-04-18 12:26:12 +01:00
|
|
|
|
2023-02-18 16:02:57 +00:00
|
|
|
for (&threads) |*handle| {
|
2021-06-20 03:31:43 +01:00
|
|
|
handle.* = try std.Thread.spawn(.{}, struct {
|
2020-04-18 12:26:12 +01:00
|
|
|
fn thread_fn(x: u8) void {
|
2021-06-20 02:10:22 +01:00
|
|
|
_ = x;
|
2020-04-18 12:26:12 +01:00
|
|
|
global_once.call();
|
|
|
|
}
|
2021-06-20 03:31:43 +01:00
|
|
|
}.thread_fn, .{0});
|
2020-04-18 12:26:12 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-05-04 18:47:26 +01:00
|
|
|
try testing.expectEqual(@as(i32, 1), global_number);
|
2020-04-18 12:26:12 +01:00
|
|
|
}
|