atomic finished

main
Your Name 2024-07-10 13:27:26 +08:00
parent 75794439e1
commit 05e21d15c5
1 changed files with 24 additions and 1 deletions

View File

@ -1,5 +1,28 @@
package main package main
import (
"fmt"
"sync"
"sync/atomic"
)
var a int64 //并发修改a变量的值可能会导致数字错误
var WG sync.WaitGroup
//var mLock sync.Mutex //方法1,添加互斥锁
func main() { 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)
}