atomic finished
parent
75794439e1
commit
05e21d15c5
|
@ -1,5 +1,28 @@
|
|||
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)
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue