core: Add spinlock code
This commit is contained in:
parent
ea952efe8a
commit
14862ec271
24
core/src/lib/spinlock.zig
Normal file
24
core/src/lib/spinlock.zig
Normal file
@ -0,0 +1,24 @@
|
||||
const std = @import("std");
|
||||
const debug = @import("../arch/debug.zig");
|
||||
|
||||
pub const SpinLock = struct {
|
||||
lock_value: std.atomic.Value(u32) = std.atomic.Value(u32).init(0),
|
||||
|
||||
pub fn lock(self: *SpinLock) void {
|
||||
while (self.lock_value.cmpxchgWeak(0, 1, .seq_cst, .seq_cst) != null) {}
|
||||
}
|
||||
|
||||
pub fn unlock(self: *SpinLock) void {
|
||||
if (self.lock_value.cmpxchgStrong(1, 0, .seq_cst, .seq_cst) != null) {
|
||||
debug.print("Error: SpinLock.unlock() called on an unlocked lock!\n", .{});
|
||||
}
|
||||
}
|
||||
|
||||
pub fn tryLock(self: *SpinLock) bool {
|
||||
return self.lock_value.cmpxchgStrong(0, 1, .seq_cst, .seq_cst) == null;
|
||||
}
|
||||
|
||||
pub fn isLocked(self: *SpinLock) bool {
|
||||
return self.lock_value.load() != 0;
|
||||
}
|
||||
};
|
Loading…
x
Reference in New Issue
Block a user