← 中文资源

简体中文版本

Atomic Bool 交换标志

用 atomic.Bool 的 Swap 与 CompareAndSwap 在多个 goroutine 间翻转共享标志,不需要互斥锁,并观察每次返回值。

阅读英文原文

实现说明

逻辑集中在函数 main里。 在这里做循环的是 for i := 0; i < 5; i++。工作交给 goroutine 执行。入口处 defer、出口处执行:defer 让清理与获取紧挨着写。

使用要点

  • 没有锁文件条目,没有版本钉死——除了运行时,文件什么都不需要。
  • 每一步打印都带着自己的标签:initial:、cas false to true:、cas false again:。

常见问题

运行「Atomic Bool 交换标志」会打印什么?

运行文件本身,initial:、cas false to true:、cas false again: 这些前缀各对应一段演示逻辑。

核心语句

var wg sync.WaitGroup
defer wg.Done()

代码示例

package main

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

func main() {
	var flag atomic.Bool
	fmt.Println("initial:", flag.Load())

	// CompareAndSwap writes only while the expected value still matches
	fmt.Println("cas false to true:", flag.CompareAndSwap(false, true))
	fmt.Println("cas false again:", flag.CompareAndSwap(false, true))
	flag.Store(false)

	// Swap stores a new value and returns the previous one
	switches := 0
	for i := 0; i < 5; i++ {
		previous := flag.Swap(i%2 == 0)
		if previous {
			switches++
		}
	}
	fmt.Println("after swaps:", flag.Load())
	fmt.Println("previous true count:", switches)

	var wg sync.WaitGroup
	for i := 0; i < 8; i++ {
		wg.Add(1)
		go func() {
			defer wg.Done()
			// Store and Load are individually atomic, not a combined toggle
			flag.Store(!flag.Load())
		}()
	}
	wg.Wait()
	fmt.Println("final observed:", flag.Load())
}