course/sync/atomic.go

29 lines
500 B
Go
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

package main
import (
"fmt"
"sync"
"sync/atomic"
)
var a int64 //并发修改a变量的值可能会导致数字错误
var WG sync.WaitGroup
//var mLock sync.Mutex //方法1,添加互斥锁
func main() {
for i := 0; i < 1000; i++ {
WG.Add(1)
go func() {
//mLock.Lock() //加锁
//a++ //加法操作
atomic.AddInt64(&a, 1) //传递全局变量指针,和要加的值,默认就是加锁和释放锁
//mLock.Unlock() //解锁
WG.Done()
}()
}
WG.Wait()
fmt.Println(a)
}