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) {...@@ -7,6 +7,7 @@ pub fn once(comptime f: fn () void) Once(f) {
7}7}
88
9/// An object that executes the function `f` just once.9/// An object that executes the function `f` just once.
10/// It is undefined behavior if `f` re-enters the same Once instance.
10pub fn Once(comptime f: fn () void) type {11pub fn Once(comptime f: fn () void) type {
11 return struct {12 return struct {
12 done: bool = false,13 done: bool = false,
...@@ -51,15 +52,18 @@ test "Once executes its function just once" {...@@ -51,15 +52,18 @@ test "Once executes its function just once" {
51 global_once.call();52 global_once.call();
52 } else {53 } else {
53 var threads: [10]std.Thread = undefined;54 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
56 for (&threads) |*handle| {58 for (&threads) |*handle| {
57 handle.* = try std.Thread.spawn(.{}, struct {59 handle.* = try std.Thread.spawn(.{}, struct {
58 fn thread_fn(x: u8) void {60 fn thread_fn(x: u8) void {
59 _ = x;61 _ = x;
60 global_once.call();62 global_once.call();
63 if (global_number != 1) @panic("memory ordering bug");
61 }64 }
62 }.thread_fn, .{0});65 }.thread_fn, .{0});
66 thread_count += 1;
63 }67 }
64 }68 }
6569