Atomic Bitwise Flags Without A Mutex

Update shared flag bitmasks from many goroutines without a mutex: atomic.Or sets bits, atomic.And clears them, and LoadInt64 reads the final snapshot.

GoConfig Management

Code

snippet
package main

import (
	"fmt"
	"sync"
	"sync/atomic"
)

func main() {
	var flags int64 // bit0=灰度发布 bit1=调试日志 bit2=导出
	var wg sync.WaitGroup

	// Go 1.23 起的原子按位操作:多个 goroutine 并发改位,无锁无丢失
	wg.Add(3)
	go func() { defer wg.Done(); atomic.Or(&flags, 1<<0) }()
	go func() { defer wg.Done(); atomic.Or(&flags, 1<<1) }()
	go func() { defer wg.Done(); atomic.And(&flags, ^(1 << 2)) }()
	wg.Wait()

	state := atomic.LoadInt64(&flags)
	fmt.Printf("flags=%03b\n", state)
	fmt.Println("rollout:", state&1 != 0)
	fmt.Println("debug:", state&2 != 0)
	fmt.Println("export:", state&4 != 0)
}

Lock-free bit updates from three goroutines

Three goroutines run concurrently against one int64: two set bits with atomic.Or(&flags, 1<<0) and atomic.Or(&flags, 1<<1), and the third clears bit 2 with atomic.And(&flags, ^(1 << 2)). The bit-operations commute for this data — nothing sets bit 2 — so the final state is the same regardless of scheduling, with no mutex anywhere in the file. wg.Wait() joins the three, then atomic.LoadInt64(&flags) reads the snapshot.

The final state, printed bitwise

flags=011
rollout: true
debug: true
export: false

fmt.Printf("flags=%03b\n", state) renders the mask as three padded bits; the three following lines test individual bits with state&1 != 0, state&2 != 0, and state&4 != 0. Bit 0 (灰度发布) and bit 1 (调试日志) are set by the two Or calls; bit 2 (导出) was never set, and the And-clear leaves it at zero.

The line that clears safely

go func() { defer wg.Done(); atomic.And(&flags, ^(1 << 2)) }()

^(1 << 2) is the complement mask — every bit except bit 2 stays 1, so the And touches only that bit — and each goroutine attaches defer wg.Done() so WaitGroup accounting cannot be skipped on any exit path.

Interactive Tools for This Topic

FAQ

What does Atomic Bitwise Flags Without A Mutex print when run?
Running the file directly is enough — expect labeled output lines such as `flags=`, `rollout:`, `debug:`.