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