美文网首页
Golang sync.Mutex用法(互斥量用法)

Golang sync.Mutex用法(互斥量用法)

作者: FredricZhu | 来源:发表于2019-06-08 10:39 被阅读0次
package main

import (
    "fmt"
    "sync"
)

func main() {
    var count int
    var lock sync.Mutex
    var arthmatic sync.WaitGroup

    Increment := func() {
        lock.Lock()
        defer lock.Unlock()
        count++
        fmt.Printf("Incrementing: %d\n", count)
    }

    Decrement := func() {
        lock.Lock()
        defer lock.Unlock()
        count--
        fmt.Printf("Decrementing: %d\n", count)
    }

    for i := 0; i < 5; i++ {
        arthmatic.Add(1)
        go func() {
            defer arthmatic.Done()
            Increment()
        }()
    }

    for i := 0; i < 5; i++ {
        arthmatic.Add(1)
        go func() {
            defer arthmatic.Done()
            Decrement()
        }()
    }

    arthmatic.Wait()
    fmt.Printf("Arthmatic completed!\n")
}

程序输出如下,


image.png

相关文章

网友评论

      本文标题:Golang sync.Mutex用法(互斥量用法)

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