互斥鎖
-
互斥鎖的是控制共享資源進(jìn)行訪問的主要手段,目的是來保證在同一時(shí)刻只有一個(gè)線程對該對象進(jìn)行訪問遂铡。類似于開箱關(guān)箱子
golang中提供了一個(gè)sync.Mutex類型,并提供了一個(gè)Lock和UnLock方法,含義于圖中相似。
下面是測試互斥鎖的使用
package main
import (
"fmt"
"sync"
"time"
)
var m *sync.Mutex
var goruntimeWaitGroup sync.WaitGroup
func main() {
m = new(sync.Mutex)
goruntimeWaitGroup.Add(1)
go Worker(1, 5)
goruntimeWaitGroup.Add(1)
go Worker(2, 1)
goruntimeWaitGroup.Add(1)
go Worker(3, 1)
goruntimeWaitGroup.Add(1)
go Worker(4, 1)
goruntimeWaitGroup.Add(1)
go Worker(5, 3)
goruntimeWaitGroup.Wait()
fmt.Println("main Exit")
}
func Worker(i int, workerTime time.Duration) {
defer goruntimeWaitGroup.Done()
fmt.Println(i, "worker start")
fmt.Println(i, "worker in lock")
m.Lock()
defer fmt.Println(i, "unlock")
defer m.Unlock()
fmt.Println("worker runing")
time.Sleep(workerTime * time.Second)
}
運(yùn)行結(jié)果:
4 worker start
4 worker in lock
worker runing
2 worker start
2 worker in lock
5 worker start
5 worker in lock
1 worker start
1 worker in lock
3 worker start
3 worker in lock
4 unlock
worker runing
2 unlock
worker runing
5 unlock
worker runing
1 unlock
worker runing
3 unlock
main Exit
解讀:
- 互斥鎖需成對出現(xiàn)恒水,可以運(yùn)用defer防止中間return,忘記寫unclock造成死鎖饲齐。
- 可以驗(yàn)證互斥鎖的作用會(huì)保護(hù)共享資源钉凌,使同一時(shí)刻只有一個(gè)對象訪問。