1 原子锁
可以借助某个信号向所有的goroutine 发送消息
var (
shotdown int64 // 该标志向多个goroutine通知状态
wg sync.WaitGroup
)
func main() {
wg.Add(2)
go doWork("A")
go doWork("B")
time.Sleep(1 * time.Second)
atomic.StoreInt64(&shotdown, 1) // 修改
wg.Wait()
}
func doWork(s string) {
defer wg.Done()
for {
fmt.Printf("Doing homework %s\n", s)
time.Sleep(2 * time.Second)
if atomic.LoadInt64(&shotdown) == 1 { // 读取
fmt.Printf("Shotdown home work %s\n", s)
break
}
}
}
2 互斥锁
互斥锁,通过 mutex, 能够将一段临界区间包含起来,只运行单个goroutine执行
// 借助互斥锁实现同步访问共享资源
var (
counter int
wg sync.WaitGroup
mutex sync.Mutex // 定义临界区
)
func main() {
wg.Add(2)
go incCount(1)
go incCount(2)
wg.Wait()
fmt.Printf("Final Counter: %d\n", counter)
}
func incCount(i int) {
defer wg.Done()
for count := 0; count < 2; count++ {
mutex.Lock()
{
value := counter
runtime.Gosched()
value++
counter = value
}
mutex.Unlock()
}
}