zig/lib/std/event/locked.zig

43 lines
1.1 KiB
Zig
Raw Normal View History

2019-03-03 05:46:04 +08:00
const std = @import("../std.zig");
2018-07-10 10:22:44 +08:00
const Lock = std.event.Lock;
/// Thread-safe async/await lock that protects one piece of data.
/// Functions which are waiting for the lock are suspended, and
2018-07-10 10:22:44 +08:00
/// are resumed when the lock is released, in order.
pub fn Locked(comptime T: type) type {
return struct {
2018-07-10 10:22:44 +08:00
lock: Lock,
private_data: T,
const Self = @This();
2018-07-10 10:22:44 +08:00
pub const HeldLock = struct {
2018-07-10 10:22:44 +08:00
value: *T,
held: Lock.Held,
pub fn release(self: HeldLock) void {
self.held.release();
}
};
pub fn init(data: T) Self {
return Self{
.lock = Lock.init(),
2018-07-10 10:22:44 +08:00
.private_data = data,
};
}
pub fn deinit(self: *Self) void {
self.lock.deinit();
}
pub async fn acquire(self: *Self) HeldLock {
return HeldLock{
2019-05-13 00:56:01 +08:00
// TODO guaranteed allocation elision
.held = self.lock.acquire(),
2018-07-10 10:22:44 +08:00
.value = &self.private_data,
};
}
};
}