Microkernel thing OS experiment (Zig ⚡)
1const std = @import("std");
2const testing = std.testing;
3const builtin = @import("builtin");
4const Thread = std.Thread;
5
6pub const Spinlock = struct {
7 const Self = @This();
8 const State = enum(u8) { Unlocked = 0, Locked };
9 const AtomicState = std.atomic.Value(State);
10
11 value: AtomicState = AtomicState.init(.Unlocked),
12
13 pub fn lock(self: *Self) void {
14 while (true) {
15 switch (self.value.swap(.Locked, .acquire)) {
16 .Locked => {},
17 .Unlocked => break,
18 }
19 }
20 }
21
22 pub fn tryLock(self: *Self) bool {
23 return switch (self.value.swap(.Locked, .acquire)) {
24 .Locked => return false,
25 .Unlocked => return true,
26 };
27 }
28
29 pub fn unlock(self: *Self) void {
30 self.value.store(.Unlocked, .release);
31 }
32};
33
34test "basics" {
35 var lock: Spinlock = .{};
36
37 lock.lock();
38 try testing.expect(!lock.tryLock());
39 lock.unlock();
40
41 try testing.expect(lock.tryLock());
42 try testing.expect(!lock.tryLock());
43 lock.unlock();
44}