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