golang使用锁

2022-08-05  本文已影响0人  耍帅oldboy
package main

import (
    "fmt"
    "sync"
    "time"
)

var count = 0
var wg sync.WaitGroup
var mutex sync.Mutex

func calc() {
    mutex.Lock()
    count++
    fmt.Println("count=", count)
    time.Sleep(time.Millisecond * 10)
    mutex.Unlock()
    wg.Done()
}

func main() {
    for i := 0; i < 20; i++ {
        wg.Add(1)
        go calc()
    }
    wg.Wait()
}

执行结果

count= 1
count= 2
count= 3
count= 4
count= 5
count= 6
count= 7
count= 8
count= 9
count= 10
count= 11
count= 12
count= 13
count= 14
count= 15
count= 16
count= 17
count= 18
count= 19
count= 20
上一篇 下一篇

猜你喜欢

热点阅读