zig/lib/std/event/locked.zig

44 lines
1.1 KiB
Zig
Raw Normal View History

2019-03-02 13:46:04 -08:00
const std = @import("../std.zig");
2018-07-09 19:22:44 -07:00
const Lock = std.event.Lock;
2018-07-09 20:41:28 -07:00
const Loop = std.event.Loop;
2018-07-09 19:22:44 -07:00
/// Thread-safe async/await lock that protects one piece of data.
/// Functions which are waiting for the lock are suspended, and
2018-07-09 19:22:44 -07:00
/// are resumed when the lock is released, in order.
pub fn Locked(comptime T: type) type {
return struct {
2018-07-09 19:22:44 -07:00
lock: Lock,
private_data: T,
const Self = @This();
2018-07-09 19:22:44 -07:00
pub const HeldLock = struct {
2018-07-09 19:22:44 -07: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-09 19:22:44 -07: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{
2019-05-12 09:56:01 -07:00
// TODO guaranteed allocation elision
2018-07-09 19:22:44 -07:00
.held = await (async self.lock.acquire() catch unreachable),
.value = &self.private_data,
};
}
};
}