mirror of
https://github.com/ziglang/zig.git
synced 2025-12-24 07:03:11 +00:00
std: add test for Thread.Semaphore
This commit is contained in:
parent
4efd951801
commit
bdd1a9e48c
@ -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);
|
||||
}
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user