| 1 |
// atomic_bitfield.go - packed visited bitfield using atomic bit ops |
| 2 |
// |
| 3 |
// Replaces per-node atomic.Bool with a shared []uint64 bitfield. |
| 4 |
// For a 1M-entry cache, this uses 16KB instead of 4MB. |
| 5 |
// |
| 6 |
// Mark/Clear use atomic.OrUint64/AndUint64 (single locked instruction, |
| 7 |
// no CAS retry loop) with a fast-path load check to skip the locked |
| 8 |
// instruction when the bit is already in the desired state. |
| 9 |
// IsVisited is a single atomic load — zero contention on the read path. |
| 10 |
|
| 11 |
package sieve |
| 12 |
|
| 13 |
import "sync/atomic" |
| 14 |
|
| 15 |
// atomicBitfield is a packed bitfield for tracking visited status of cache nodes. |
| 16 |
// Each bit corresponds to one node index. Thread-safe via atomic operations. |
| 17 |
type atomicBitfield struct { |
| 18 |
words []uint64 |
| 19 |
} |
| 20 |
|
| 21 |
var _ visitor = &atomicBitfield{} |
| 22 |
|
| 23 |
// newAtomicBitfield creates an atomicBitfield with enough words for capacity bits. |
| 24 |
func newAtomicBitfield(capacity int) *atomicBitfield { |
| 25 |
nwords := (capacity + 63) / 64 |
| 26 |
return &atomicBitfield{ |
| 27 |
words: make([]uint64, nwords), |
| 28 |
} |
| 29 |
} |
| 30 |
|
| 31 |
// Mark sets the visited bit for node at idx. |
| 32 |
func (vb *atomicBitfield) Mark(idx int32) { |
| 33 |
w := idx / 64 |
| 34 |
word := &vb.words[w] |
| 35 |
bit := uint64(1) << (idx % 64) |
| 36 |
if atomic.LoadUint64(word)&bit != 0 { |
| 37 |
return // already set — skip the locked instruction |
| 38 |
} |
| 39 |
atomic.OrUint64(word, bit) |
| 40 |
} |
| 41 |
|
| 42 |
// Clear clears the visited bit for node at idx. |
| 43 |
func (vb *atomicBitfield) Clear(idx int32) { |
| 44 |
w := idx / 64 |
| 45 |
word := &vb.words[w] |
| 46 |
bit := uint64(1) << (idx % 64) |
| 47 |
if atomic.LoadUint64(word)&bit == 0 { |
| 48 |
return |
| 49 |
} |
| 50 |
atomic.AndUint64(word, ^bit) |
| 51 |
} |
| 52 |
|
| 53 |
// Reset clears the visited bit for node at idx (same as Clear for a bitfield). |
| 54 |
func (vb *atomicBitfield) Reset(idx int32) { |
| 55 |
vb.Clear(idx) |
| 56 |
} |
| 57 |
|
| 58 |
// IsVisited returns true if the visited bit for node at idx is set. |
| 59 |
// Single atomic load — no CAS, no contention. |
| 60 |
func (vb *atomicBitfield) IsVisited(idx int32) bool { |
| 61 |
w := idx / 64 |
| 62 |
word := &vb.words[w] |
| 63 |
bit := uint64(1) << (idx % 64) |
| 64 |
return atomic.LoadUint64(word)&bit != 0 |
| 65 |
} |
| 66 |
|
| 67 |
// ResetAll clears all visited bits. Called from Purge() under s.mu — plain stores are fine. |
| 68 |
func (vb *atomicBitfield) ResetAll() { |
| 69 |
for i := range vb.words { |
| 70 |
vb.words[i] = 0 |
| 71 |
} |
| 72 |
} |