2019-03-02 13:46:04 -08:00
|
|
|
const std = @import("../std.zig");
|
2018-08-01 13:26:37 -07:00
|
|
|
const RwLock = std.event.RwLock;
|
|
|
|
|
|
|
|
/// Thread-safe async/await RW lock that protects one piece of data.
|
2019-08-13 11:14:19 -07:00
|
|
|
/// Functions which are waiting for the lock are suspended, and
|
2018-08-01 13:26:37 -07:00
|
|
|
/// are resumed when the lock is released, in order.
|
|
|
|
pub fn RwLocked(comptime T: type) type {
|
2018-11-13 05:08:37 -08:00
|
|
|
return struct {
|
2018-08-01 13:26:37 -07:00
|
|
|
lock: RwLock,
|
|
|
|
locked_data: T,
|
|
|
|
|
2018-09-13 13:34:33 -07:00
|
|
|
const Self = @This();
|
2018-08-01 13:26:37 -07:00
|
|
|
|
2018-11-13 05:08:37 -08:00
|
|
|
pub const HeldReadLock = struct {
|
2018-08-01 13:26:37 -07:00
|
|
|
value: *const T,
|
|
|
|
held: RwLock.HeldRead,
|
|
|
|
|
|
|
|
pub fn release(self: HeldReadLock) void {
|
|
|
|
self.held.release();
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2018-11-13 05:08:37 -08:00
|
|
|
pub const HeldWriteLock = struct {
|
2018-08-01 13:26:37 -07:00
|
|
|
value: *T,
|
|
|
|
held: RwLock.HeldWrite,
|
|
|
|
|
|
|
|
pub fn release(self: HeldWriteLock) void {
|
|
|
|
self.held.release();
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2019-11-06 11:41:35 -08:00
|
|
|
pub fn init(data: T) Self {
|
2018-11-13 05:08:37 -08:00
|
|
|
return Self{
|
2019-11-06 11:41:35 -08:00
|
|
|
.lock = RwLock.init(),
|
2018-08-01 13:26:37 -07:00
|
|
|
.locked_data = data,
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn deinit(self: *Self) void {
|
|
|
|
self.lock.deinit();
|
|
|
|
}
|
|
|
|
|
2020-05-04 08:49:27 -07:00
|
|
|
pub fn acquireRead(self: *Self) callconv(.Async) HeldReadLock {
|
2018-11-13 05:08:37 -08:00
|
|
|
return HeldReadLock{
|
2019-11-06 11:41:35 -08:00
|
|
|
.held = self.lock.acquireRead(),
|
2018-08-01 13:26:37 -07:00
|
|
|
.value = &self.locked_data,
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
2020-05-04 08:49:27 -07:00
|
|
|
pub fn acquireWrite(self: *Self) callconv(.Async) HeldWriteLock {
|
2018-11-13 05:08:37 -08:00
|
|
|
return HeldWriteLock{
|
2019-11-06 11:41:35 -08:00
|
|
|
.held = self.lock.acquireWrite(),
|
2018-08-01 13:26:37 -07:00
|
|
|
.value = &self.locked_data,
|
|
|
|
};
|
|
|
|
}
|
|
|
|
};
|
|
|
|
}
|