authorgravatar for aleksey.kladov@gmail.comAlex Kladov <aleksey.kladov@gmail.com> 2024-04-15 13:57:41+01:00
committergravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2024-04-15 15:24:30-07:00
logff18103ef6d383b6c6f81d996925f3a7856851e9
tree9945d6abc1ed66b8c47e5b04e751f204bfd391cf
parent1e5075f81296cccd469a0829259231cb34337a02

std: improve std.once tests

* fix UB when Thread.spawn fails, and we try to join uninitialized threads (through new `thread_count` variable). * make sure that the tests pins down synchronization guarantees: in the main thread, we can observe `1` due to synchronization from `Thread.join()`. To make sure that once uses Acq/Rel, and not just relaxed, we should also additionally check that each thread observes 1, regardless of whether it was the one to call once.

1 files changed, 5 insertions(+), 1 deletions(-)

lib/std/once.zig+5-1
......@@ -7,6 +7,7 @@ pub fn once(comptime f: fn () void) Once(f) {
77}
88
99/// An object that executes the function `f` just once.
10/// It is undefined behavior if `f` re-enters the same Once instance.
1011pub fn Once(comptime f: fn () void) type {
1112 return struct {
1213 done: bool = false,
......@@ -51,15 +52,18 @@ test "Once executes its function just once" {
5152 global_once.call();
5253 } else {
5354 var threads: [10]std.Thread = undefined;
54 defer for (threads) |handle| handle.join();
55 var thread_count: usize = 0;
56 defer for (threads[0..thread_count]) |handle| handle.join();
5557
5658 for (&threads) |*handle| {
5759 handle.* = try std.Thread.spawn(.{}, struct {
5860 fn thread_fn(x: u8) void {
5961 _ = x;
6062 global_once.call();
63 if (global_number != 1) @panic("memory ordering bug");
6164 }
6265 }.thread_fn, .{0});
66 thread_count += 1;
6367 }
6468 }
6569