对于互斥锁:
不要重复锁没锁不要解锁不要赋值/函数间传递/函数返回锁定, 紧接着 defer 解锁
对于读写锁:
读锁 + 读锁 不阻塞其他都阻塞
上代码, 自己品:
package mainimport ("fmt""sync""time")var i = 0func count() int {i++return i}func main() {var locker sync.Mutexfor i := 0; i < 10; i++ {go func(i int) {locker.Lock()defer locker.Unlock()fmt.Printf("%d: %dn", i, count())time.Sleep(time.Millisecond * 200)}(i)}time.Sleep(time.Second * 5)}
package mainimport ("sync")func main() {var locker sync.Mutexlocker.Lock()locker.Lock() // fatal error: all goroutines are asleep - deadlock!defer locker.Unlock()}
package mainimport ("sync""time")func main() {var locker sync.Mutexgo func() {locker.Lock()locker.Lock() // 阻塞在这里, 没有错误信息, 也没有 panicdefer locker.Unlock()}()time.Sleep(time.Second * 5)}
package mainimport ("fmt""sync")func main() {var locker sync.Mutexlocker.Unlock() // fatal error: sync: unlock of unlocked mutexfmt.Println("done")}
package mainimport ("fmt""sync")func main() {var locker sync.Mutexlocker.Lock()locker.Unlock()locker.Unlock() // fatal error: sync: unlock of unlocked mutexfmt.Println("done")}
package mainimport ("fmt""sync""time")func main() {var locker sync.Mutexgo func() {locker.Unlock() // fatal error: sync: unlock of unlocked mutexfmt.Println("done")}()time.Sleep(time.Second * 2)}
package mainimport ("fmt""sync")func main() {var locker sync.Mutexlocker2 := locker // lock2 是 locker 的副本, 不一样了locker.Lock()locker2.Lock() // 没有阻塞defer locker2.Unlock()defer locker.Unlock()fmt.Println("done")}
package mainimport ("fmt""sync""time")func main() {var locker sync.Mutexgo func() {locker.Lock()defer locker.Unlock()time.Sleep(time.Second * 2)fmt.Println("aaa")}()go func() {locker.Lock()defer locker.Unlock()time.Sleep(time.Second * 2)fmt.Println("bbb")}()time.Sleep(time.Second * 5)}
package mainimport ("fmt""sync""time")func main() {var locker sync.Mutexlocker2 := lockergo func() {locker.Lock()defer locker.Unlock()time.Sleep(time.Second * 2)fmt.Println("aaa")}()go func() {locker2.Lock()defer locker2.Unlock()time.Sleep(time.Second * 2)fmt.Println("bbb")}()time.Sleep(time.Second * 5)}
package mainimport ("sync")func main() {var locker sync.RWMutexlocker.Lock()locker.Lock() // fatal error: all goroutines are asleep - deadlock!defer locker.Unlock()defer locker.Unlock()}
package mainimport ("sync")func main() {var locker sync.RWMutexlocker.Lock()locker.RLock() // fatal error: all goroutines are asleep - deadlock!defer locker.Unlock()defer locker.RUnlock()}
package mainimport ("sync")func main() {var locker sync.RWMutexlocker.RLock()locker.Lock() // fatal error: all goroutines are asleep - deadlock!defer locker.RUnlock()defer locker.Unlock()}
package mainimport ("fmt""sync")func main() {var locker sync.RWMutexlocker.RLock()locker.RLock()defer locker.RUnlock()defer locker.RUnlock()fmt.Println("done") // done}
package mainimport ("fmt""sync")func main() {var locker sync.RWMutexrlocker := locker.RLocker()rlocker.Lock()rlocker.Lock()defer rlocker.Unlock()defer rlocker.Unlock()fmt.Println("done") // done}