Debian Codegraph @

exp/spinlock.go

raw
1 // spinlock.go - per-slot exclusive spinlock using uint32 atomics
2 //
3 // Column-oriented per-node synchronization: one uint32 per lock slot.
4 // 16 locks per cache line (64 bytes / 4 bytes), reducing false sharing
5 // compared to the packed 1-bit layout (512 locks per cache line).
6 //
7 // For 1M entries this is 4 MB. The tradeoff is more memory for less
8 // false sharing on concurrent atomic ops across different slots.
9 //
10 // On the uncontended fast path:
11 // Lock: 1 atomic.CompareAndSwapUint64
12 // Unlock: 1 atomic.StoreUint64
13
14 package sieve
15
16 import (
17 "sync/atomic"
18 )
19
20 // spinlock is an array of per-slot exclusive spinlocks.
21 // One uint32 per node index: 0 = unlocked, 1 = locked.
22 type spinlock struct {
23 slots []uint64
24 }
25
26 // newSpinlock creates a spinlock array for the given capacity.
27 func newSpinlock(capacity int) *spinlock {
28 return &spinlock{
29 slots: make([]uint64, capacity),
30 }
31 }
32
33 // Lock acquires an exclusive lock for the node at idx.
34 func (sl *spinlock) Lock(idx int32) {
35 slot := &sl.slots[idx]
36 for i := 0; ; i++ {
37 if atomic.CompareAndSwapUint64(slot, 0, 1) {
38 return
39 }
40 pause(i)
41 }
42 }
43
44 // Unlock releases an exclusive lock for the node at idx.
45 func (sl *spinlock) Unlock(idx int32) {
46 atomic.StoreUint64(&sl.slots[idx], 0)
47 }
48
49 // ResetAll clears all lock state. Called from Purge() under s.mu.
50 func (sl *spinlock) ResetAll() {
51 for i := range sl.slots {
52 sl.slots[i] = 0
53 }
54 }