传统同步机制(很少使用)包括WaitGroup,Mutex和Cond等。

    Mutex(互斥量):

    1. import(
    2. "fmt"
    3. "sync"
    4. "time"
    5. )
    6. // 原子化的Int
    7. type atomicInt struct {
    8. value int
    9. lock sync.Mutex
    10. }
    11. func (a *atomicInt) increment() {
    12. a.lock.Lock()
    13. defer a.lock.Unlock()
    14. a.value++
    15. }
    16. func (a *atomicInt) get() int {
    17. a.lock.Lock()
    18. defer a.lock.Unlock()
    19. return a.value
    20. }
    21. func main() {
    22. var a atomicInt
    23. a.increment()
    24. go func() {
    25. a.increment()
    26. }()
    27. time.Sleep(time.Millisecond)
    28. fmt.Println(a.get()) // 2
    29. }

    对一个代码区进行上锁:

    // 把要上锁的代码区放入一个匿名函数,就完成了对该代码区的上锁
    func (a *atomicInt) increment() {
        fmt.Println("safe increment")
        func() {
            a.lock.Lock()
            defer a.lock.Unlock()
    
            a.value++
        }()
    }