authorgravatar for 36885263+naeu@users.noreply.github.comnaeu <36885263+naeu@users.noreply.github.com> 2022-01-29 19:17:37+00:00
committergravatar for 36885263+naeu@users.noreply.github.comnaeu <36885263+naeu@users.noreply.github.com> 2022-01-29 20:30:53+00:00
logbdd1a9e48c7a1a09cf0a3b7c0d5be6547f8ef1aa
treeae498c8406341ce1b54bb78cdc4e95775ae80d6a
parent4efd95180166e602402142eb64d77f97b48ddb3c

std: add test for Thread.Semaphore


1 files changed, 28 insertions(+), 0 deletions(-)

lib/std/Thread/Semaphore.zig+28
......@@ -11,6 +11,8 @@ const Semaphore = @This();
1111const std = @import("../std.zig");
1212const Mutex = std.Thread.Mutex;
1313const Condition = std.Thread.Condition;
14const builtin = @import("builtin");
15const testing = std.testing;
1416
1517pub fn wait(sem: *Semaphore) void {
1618 sem.mutex.lock();
......@@ -31,3 +33,29 @@ pub fn post(sem: *Semaphore) void {
3133 sem.permits += 1;
3234 sem.cond.signal();
3335}
36
37test "Thread.Semaphore" {
38 if (builtin.single_threaded) {
39 return error.SkipZigTest;
40 }
41
42 const TestContext = struct {
43 sem: *Semaphore,
44 n: *i32,
45 fn worker(ctx: *@This()) void {
46 ctx.sem.wait();
47 ctx.n.* += 1;
48 ctx.sem.post();
49 }
50 };
51 const num_threads = 3;
52 var sem = Semaphore{ .permits = 1 };
53 var threads: [num_threads]std.Thread = undefined;
54 var n: i32 = 0;
55 var ctx = TestContext{ .sem = &sem, .n = &n };
56
57 for (threads) |*t| t.* = try std.Thread.spawn(.{}, TestContext.worker, .{&ctx});
58 for (threads) |t| t.join();
59 sem.wait();
60 try testing.expect(n == num_threads);
61}