| 1 |
// spinlock_packed.go - packed exclusive spinlock using atomic bit ops |
| 2 |
// |
| 3 |
// Column-oriented per-node synchronization: 1 bit per lock slot, |
| 4 |
// 64 locks packed into each uint64 word. For 1M entries this is |
| 5 |
// 16 KB (same layout as the visited bitfield). |
| 6 |
// |
| 7 |
// Every lock/unlock (both Get and Add paths) is exclusive. |
| 8 |
// The critical section is a single field read or write (~1 ns), |
| 9 |
// so reader-reader serialization is negligible compared to the |
| 10 |
// CAS overhead of a reader-writer scheme. |
| 11 |
// |
| 12 |
// On the uncontended fast path: |
| 13 |
// Lock: 1 atomic.OrUint64 (test-and-set in one instruction) |
| 14 |
// Unlock: 1 atomic.AndUint64 |
| 15 |
|
| 16 |
package sieve |
| 17 |
|
| 18 |
import ( |
| 19 |
"runtime" |
| 20 |
"sync/atomic" |
| 21 |
) |
| 22 |
|
| 23 |
const ( |
| 24 |
packedSlotsPerWord = 64 |
| 25 |
) |
| 26 |
|
| 27 |
// packedSpinlock is a packed array of exclusive spinlocks. |
| 28 |
// 64 locks per uint64 word, one lock per node index. |
| 29 |
type packedSpinlock struct { |
| 30 |
words []uint64 |
| 31 |
} |
| 32 |
|
| 33 |
// newPackedSpinlock creates a packed spinlock array for the given capacity. |
| 34 |
func newPackedSpinlock(capacity int) *packedSpinlock { |
| 35 |
nwords := (capacity + packedSlotsPerWord - 1) / packedSlotsPerWord |
| 36 |
return &packedSpinlock{ |
| 37 |
words: make([]uint64, nwords), |
| 38 |
} |
| 39 |
} |
| 40 |
|
| 41 |
// packedSlotPos returns the word index and bit mask for a given node index. |
| 42 |
func packedSlotPos(idx int32) (w int32, mask uint64) { |
| 43 |
w = idx / packedSlotsPerWord |
| 44 |
mask = uint64(1) << uint(idx%packedSlotsPerWord) |
| 45 |
return |
| 46 |
} |
| 47 |
|
| 48 |
// Lock acquires an exclusive lock for the node at idx. |
| 49 |
// Uses atomic.OrUint64 as a test-and-set: the returned old value |
| 50 |
// tells us whether we won the race (bit was clear) or need to spin. |
| 51 |
// OR of a 1 onto an existing 1 is idempotent — no harm if we lose. |
| 52 |
func (sl *packedSpinlock) Lock(idx int32) { |
| 53 |
w, mask := packedSlotPos(idx) |
| 54 |
word := &sl.words[w] |
| 55 |
|
| 56 |
for { |
| 57 |
old := atomic.OrUint64(word, mask) |
| 58 |
if old&mask == 0 { |
| 59 |
// Bit was clear — we acquired it |
| 60 |
return |
| 61 |
} |
| 62 |
// Already locked — spin |
| 63 |
runtime.Gosched() |
| 64 |
} |
| 65 |
} |
| 66 |
|
| 67 |
// Unlock releases an exclusive lock for the node at idx. |
| 68 |
func (sl *packedSpinlock) Unlock(idx int32) { |
| 69 |
w, mask := packedSlotPos(idx) |
| 70 |
atomic.AndUint64(&sl.words[w], ^mask) |
| 71 |
} |
| 72 |
|
| 73 |
// ResetAll clears all lock state. Called from Purge() under s.mu. |
| 74 |
func (sl *packedSpinlock) ResetAll() { |
| 75 |
for i := range sl.words { |
| 76 |
sl.words[i] = 0 |
| 77 |
} |
| 78 |
} |