mirror of
https://github.com/ziglang/zig.git
synced 2025-12-06 14:23:09 +00:00
This is a breaking change. Before, usage looked like this: ```zig const held = mutex.acquire(); defer held.release(); ``` Now it looks like this: ```zig mutex.lock(); defer mutex.unlock(); ``` The `Held` type was an idea to make mutexes slightly safer by making it more difficult to forget to release an aquired lock. However, this ultimately caused more problems than it solved, when any data structures needed to store a held mutex. Simplify everything by reducing the API down to the primitives: lock() and unlock(). Closes #8051 Closes #8246 Closes #10105
34 lines
812 B
Zig
34 lines
812 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 {
|
|
sem.mutex.lock();
|
|
defer sem.mutex.unlock();
|
|
|
|
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 {
|
|
sem.mutex.lock();
|
|
defer sem.mutex.unlock();
|
|
|
|
sem.permits += 1;
|
|
sem.cond.signal();
|
|
}
|