mirror of
https://github.com/ziglang/zig.git
synced 2025-12-06 22:33:08 +00:00
We already have a LICENSE file that covers the Zig Standard Library. We no longer need to remind everyone that the license is MIT in every single file. Previously this was introduced to clarify the situation for a fork of Zig that made Zig's LICENSE file harder to find, and replaced it with their own license that required annual payments to their company. However that fork now appears to be dead. So there is no need to reinforce the copyright notice in every single file.
34 lines
836 B
Zig
34 lines
836 B
Zig
//! A semaphore is an unsigned integer that blocks the kernel thread if
|
|
//! the number would become negative.
|
|
//! This API supports static initialization and does not require deinitialization.
|
|
|
|
mutex: Mutex = .{},
|
|
cond: Condition = .{},
|
|
/// It is OK to initialize this field to any value.
|
|
permits: usize = 0,
|
|
|
|
const Semaphore = @This();
|
|
const std = @import("../std.zig");
|
|
const Mutex = std.Thread.Mutex;
|
|
const Condition = std.Thread.Condition;
|
|
|
|
pub fn wait(sem: *Semaphore) void {
|
|
const held = sem.mutex.acquire();
|
|
defer held.release();
|
|
|
|
while (sem.permits == 0)
|
|
sem.cond.wait(&sem.mutex);
|
|
|
|
sem.permits -= 1;
|
|
if (sem.permits > 0)
|
|
sem.cond.signal();
|
|
}
|
|
|
|
pub fn post(sem: *Semaphore) void {
|
|
const held = sem.mutex.acquire();
|
|
defer held.release();
|
|
|
|
sem.permits += 1;
|
|
sem.cond.signal();
|
|
}
|