| ... | ... | @@ -27,20 +27,24 @@ pub const Lock = struct { |
| 27 | 27 | |
| 28 | 28 | const Waiter = struct { |
| 29 | 29 | // forced Waiter alignment to ensure it doesn't clash with LOCKED |
| 30 | | next: ?*Waiter align(2), |
| 30 | next: ?*Waiter align(2), |
| 31 | 31 | tail: *Waiter, |
| 32 | 32 | node: Loop.NextTickNode, |
| 33 | 33 | }; |
| 34 | 34 | |
| 35 | pub fn initLocked() Lock { |
| 36 | return Lock{ .head = LOCKED }; |
| 37 | } |
| 38 | |
| 35 | 39 | pub fn acquire(self: *Lock) Held { |
| 36 | 40 | const held = self.mutex.acquire(); |
| 37 | 41 | |
| 38 | 42 | // self.head transitions from multiple stages depending on the value: |
| 39 | | // UNLOCKED -> LOCKED: |
| 43 | // UNLOCKED -> LOCKED: |
| 40 | 44 | // acquire Lock ownership when theres no waiters |
| 41 | 45 | // LOCKED -> <Waiter head ptr>: |
| 42 | 46 | // Lock is already owned, enqueue first Waiter |
| 43 | | // <head ptr> -> <head ptr>: |
| 47 | // <head ptr> -> <head ptr>: |
| 44 | 48 | // Lock is owned with pending waiters. Push our waiter to the queue. |
| 45 | 49 | |
| 46 | 50 | if (self.head == UNLOCKED) { |
| ... | ... | @@ -51,7 +55,7 @@ pub const Lock = struct { |
| 51 | 55 | |
| 52 | 56 | var waiter: Waiter = undefined; |
| 53 | 57 | waiter.next = null; |
| 54 | | waiter.tail = &waiter; |
| 58 | waiter.tail = &waiter; |
| 55 | 59 | |
| 56 | 60 | const head = switch (self.head) { |
| 57 | 61 | UNLOCKED => unreachable, |
| ... | ... | @@ -79,15 +83,15 @@ pub const Lock = struct { |
| 79 | 83 | } |
| 80 | 84 | |
| 81 | 85 | pub const Held = struct { |
| 82 | | lock: *Lock, |
| 83 | | |
| 86 | lock: *Lock, |
| 87 | |
| 84 | 88 | pub fn release(self: Held) void { |
| 85 | 89 | const waiter = blk: { |
| 86 | 90 | const held = self.lock.mutex.acquire(); |
| 87 | 91 | defer held.release(); |
| 88 | 92 | |
| 89 | 93 | // self.head goes through the reverse transition from acquire(): |
| 90 | | // <head ptr> -> <new head ptr>: |
| 94 | // <head ptr> -> <new head ptr>: |
| 91 | 95 | // pop a waiter from the queue to give Lock ownership when theres still others pending |
| 92 | 96 | // <head ptr> -> LOCKED: |
| 93 | 97 | // pop the laster waiter from the queue, while also giving it lock ownership when awaken |