go变量原子操作最简单的方式就是给变量配一把锁,然后在操作这个变量的方法中都加锁放锁
如【原子int】:
type atomicInt struct {
value int
lock sync.Mutex
}
package main
import (
"fmt"
"sync"
"time"
)
type atomicInt struct {
value int
lock sync.Mutex
}
func (a *atomicInt) increase() {
a.lock.Lock()
defer a.lock.Unlock()
a.value++
}
func (a *atomicInt) get() int {
a.lock.Lock()
defer a.lock.Unlock()
return a.value
}
func main() {
var a atomicInt
for i:=0;i<10000;i++ {
go func() {
a.increase()
}()
}
time.Sleep(time.Millisecond)
fmt.Println(a.get()) // 总是10000,有锁都是串行的
}
网友评论