Uint32 Flags With CompareAndSwap

Build lock-free state flags on atomic.Uint32 with bit masks and CompareAndSwap, so a busy bit flips only when the current word still matches.

GoResilience

Code

gosnippet
36 lines
package main

import (
	"fmt"
	"sync/atomic"
)

const (
	flagBusy  uint32 = 1 << iota // 1
	flagDirty                    // 2
	flagClosed                   // 4
)

func main() {
	var state atomic.Uint32
	state.Store(flagDirty)

	// CAS 抢占 busy 位:期望值仍是 flagDirty 才交换成功
	if state.CompareAndSwap(flagDirty, flagDirty|flagBusy) {
		fmt.Println("claimed busy while dirty")
	}

	// 已带 busy 位后再次抢占:期望值不匹配,CAS 失败
	fmt.Println("second claim:", state.CompareAndSwap(flagDirty, flagDirty|flagBusy))

	// 位运算测试:& 判断某位是否已设置
	fmt.Println("busy set:", state.Load()&flagBusy != 0)
	fmt.Println("dirty set:", state.Load()&flagDirty != 0)

	// And/Or 原子改位:Or 置位、And 清位,不改其他位
	state.Or(flagClosed)
	state.And(^uint32(flagBusy))
	fmt.Println("busy after clear:", state.Load()&flagBusy != 0)
	fmt.Println("closed after or:", state.Load()&flagClosed != 0)
	fmt.Println("final word:", state.Load())
}

How it works

Uint32 Flags With CompareAndSwap comes down to the function main.

What to watch for

  • Nothing external — every call lands on the language’s built-in API surface.

Using it

Signature: func main()

The demo output is labeled (claimed busy while dirty, second claim:, busy set:), so each line traces straight back to the statement that printed it.

The key statements, annotated

flagBusy  uint32 = 1 << iota // 1

Interactive Tools for This Topic

FAQ

What does Uint32 Flags With CompareAndSwap print when run?
No setup needed: run the file and look for labeled lines like `claimed busy while dirty`, `second claim:`, `busy set:` in the output.