传统同步机制(很少使用)包括WaitGroup,Mutex和Cond等。
Mutex(互斥量):
import(
"fmt"
"sync"
"time"
)
// 原子化的Int
type atomicInt struct {
value int
lock sync.Mutex
}
func (a *atomicInt) increment() {
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
a.increment()
go func() {
a.increment()
}()
time.Sleep(time.Millisecond)
fmt.Println(a.get()) // 2
}
对一个代码区进行上锁:
// 把要上锁的代码区放入一个匿名函数,就完成了对该代码区的上锁
func (a *atomicInt) increment() {
fmt.Println("safe increment")
func() {
a.lock.Lock()
defer a.lock.Unlock()
a.value++
}()
}