Go Mutex 悲观锁

Go About 347 words

Mutex

类似于Java中的synchronizedReentrantLock

代码

进入Add函数时,使用Lock方法,紧接着直接加defer,方法退出时UnLock

var mutex sync.Mutex

func main() {
    amount := 0
    for i := 0; i < 100; i++ {
        go Add(&amount)
    }

    time.Sleep(time.Second)

    println(amount)
}

func Add(amount *int) {
    mutex.Lock()
    defer mutex.Unlock()
    *amount += 1
}
Views: 617 · Posted: 2023-09-26

————        END        ————

Give me a Star, Thanks:)

https://github.com/fendoudebb/LiteNote

扫描下方二维码关注公众号和小程序↓↓↓

扫描下方二维码关注公众号和小程序↓↓↓


Today On History
Browsing Refresh