aboutsummaryrefslogtreecommitdiff
path: root/lib/std/Thread
diff options
context:
space:
mode:
authornaeu <36885263+naeu@users.noreply.github.com>2022-01-29 19:17:37 +0000
committernaeu <36885263+naeu@users.noreply.github.com>2022-01-29 20:30:53 +0000
commitbdd1a9e48c7a1a09cf0a3b7c0d5be6547f8ef1aa (patch)
treeae498c8406341ce1b54bb78cdc4e95775ae80d6a /lib/std/Thread
parent4efd95180166e602402142eb64d77f97b48ddb3c (diff)
downloadzig-bdd1a9e48c7a1a09cf0a3b7c0d5be6547f8ef1aa.tar.gz
zig-bdd1a9e48c7a1a09cf0a3b7c0d5be6547f8ef1aa.zip
std: add test for Thread.Semaphore
Diffstat (limited to 'lib/std/Thread')
-rw-r--r--lib/std/Thread/Semaphore.zig28
1 files changed, 28 insertions, 0 deletions
diff --git a/lib/std/Thread/Semaphore.zig b/lib/std/Thread/Semaphore.zig
index 30d16037bc..72191ffd6f 100644
--- a/lib/std/Thread/Semaphore.zig
+++ b/lib/std/Thread/Semaphore.zig
@@ -11,6 +11,8 @@ const Semaphore = @This();
const std = @import("../std.zig");
const Mutex = std.Thread.Mutex;
const Condition = std.Thread.Condition;
+const builtin = @import("builtin");
+const testing = std.testing;
pub fn wait(sem: *Semaphore) void {
sem.mutex.lock();
@@ -31,3 +33,29 @@ pub fn post(sem: *Semaphore) void {
sem.permits += 1;
sem.cond.signal();
}
+
+test "Thread.Semaphore" {
+ if (builtin.single_threaded) {
+ return error.SkipZigTest;
+ }
+
+ const TestContext = struct {
+ sem: *Semaphore,
+ n: *i32,
+ fn worker(ctx: *@This()) void {
+ ctx.sem.wait();
+ ctx.n.* += 1;
+ ctx.sem.post();
+ }
+ };
+ const num_threads = 3;
+ var sem = Semaphore{ .permits = 1 };
+ var threads: [num_threads]std.Thread = undefined;
+ var n: i32 = 0;
+ var ctx = TestContext{ .sem = &sem, .n = &n };
+
+ for (threads) |*t| t.* = try std.Thread.spawn(.{}, TestContext.worker, .{&ctx});
+ for (threads) |t| t.join();
+ sem.wait();
+ try testing.expect(n == num_threads);
+}