美文网首页
golang使用锁

golang使用锁

作者: 耍帅oldboy | 来源:发表于2022-08-05 21:29 被阅读0次
    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
    

    相关文章

      网友评论

          本文标题:golang使用锁

          本文链接:https://www.haomeiwen.com/subject/hexmwrtx.html