zig/std/event/locked.zig

44 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;
2018-07-10 11:41:28 +08:00
const Loop = std.event.Loop;
2018-07-10 10:22:44 +08:00
/// Thread-safe async/await lock that protects one piece of data.
/// coroutines 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(loop: *Loop, data: T) Self {
return Self{
2018-07-10 10:22:44 +08:00
.lock = Lock.init(loop),
.private_data = data,
};
}
pub fn deinit(self: *Self) void {
self.lock.deinit();
}
pub async fn acquire(self: *Self) HeldLock {
return HeldLock{
2018-07-10 10:22:44 +08:00
// TODO guaranteed allocation elision
.held = await (async self.lock.acquire() catch unreachable),
.value = &self.private_data,
};
}
};
}