前言
GoGoMutexRWMutexWaitGroupChannel
GoMutex
说明:本文使用的代码基于的 Go 版本:1.20.1
Mutex
基本概念
MutexGogoroutinegoroutine
g1mutexg2g2
结构体介绍
字段:
state
stateint32Mutex
sema
semaMutex
方法:
Lock()
Lock()MutexMutexgoroutineLock()goroutine
UnLock()
Unlock()MutexMutex
TryLock()
Go 1.18sync.MutexTryLock()truefalse
TryLock()TryLock()
代码示例
我们先来看一个有并发安全问题的例子
cnt10 * 10000 = 100000goroutinecntrace conditioncntcnt
sync.Mutexgoroutinecnt
cntcnt++Lock()goroutinecnt++Unlock()goroutinegoroutinecnt
易错场景
忘记解锁
Lock()Unlock()goroutine
cnt3goroutinecnt12
defer
重复加锁
JavaReentrantLockGomutex
increasemugoroutine
基于 Mutex 实现一个简单的线程安全的缓存
Mutexgoroutinegoroutine
RWMutexMutexRWMutexgoroutineRWMutex
小结
GoMutexMutex
MutexMutexMutex