| ... | @@ -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 | } |
| 8 | | 8 | |
| 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. |
| 10 | pub fn Once(comptime f: fn () void) type { | 11 | pub 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(); |
| 55 | | 57 | |
| 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 | } |
| 65 | | 69 | |