go / expert
Snippet
Lock-Free Concurrent Bitset State Tracking using Atomic Bitwise Operations
Lock-free state management can be efficiently implemented over unsigned integer bitmasks using atomic Compare-And-Swap (CAS) loops. This pattern enables concurrent flag toggling without lock contention or context switching overhead.
snippet.go
go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package mainimport ("fmt""sync/atomic")type AtomicBitset struct {bits uint64}func (b *AtomicBitset) Set(pos uint8) {mask := uint64(1) << posfor {old := atomic.LoadUint64(&b.bits)if old&mask != 0 {return // Bit already set}if atomic.CompareAndSwapUint64(&b.bits, old, old|mask) {return}}}func (b *AtomicBitset) IsSet(pos uint8) bool {mask := uint64(1) << posreturn (atomic.LoadUint64(&b.bits) & mask) != 0}func main() {var bitset AtomicBitsetbitset.Set(3)bitset.Set(60)fmt.Println("Bit 3 set?", bitset.IsSet(3))fmt.Println("Bit 10 set?", bitset.IsSet(10))fmt.Println("Bit 60 set?", bitset.IsSet(60))}
Breakdown
1
for { old := atomic.LoadUint64(&b.bits) ... if atomic.CompareAndSwapUint64(&b.bits, old, old|mask) { return } }
Implements an optimistic concurrency control loop (CAS loop) that repeatedly attempts to apply the bitwise OR mask atomically until no concurrent mutation interferes.
2
return (atomic.LoadUint64(&b.bits) & mask) != 0
Atomically loads the 64-bit word state and evaluates the target bit index with a bitwise AND mask.