zig/lib/std/event/locked.zig

43 lines
1.1 KiB
Zig
Raw Normal View History

2019-03-02 21:46:04 +00:00
const std = @import("../std.zig");
2018-07-10 03:22:44 +01: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 03:22:44 +01:00
/// are resumed when the lock is released, in order.
pub fn Locked(comptime T: type) type {
return struct {
2018-07-10 03:22:44 +01:00
lock: Lock,
private_data: T,
const Self = @This();
2018-07-10 03:22:44 +01:00
pub const HeldLock = struct {
2018-07-10 03:22:44 +01: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 03:22:44 +01:00
.private_data = data,
};
}
pub fn deinit(self: *Self) void {
self.lock.deinit();
}
pub async fn acquire(self: *Self) HeldLock {
return HeldLock{
2019-05-12 17:56:01 +01:00
// TODO guaranteed allocation elision
.held = self.lock.acquire(),
2018-07-10 03:22:44 +01:00
.value = &self.private_data,
};
}
};
}