互斥锁
-
互斥锁的是控制共享资源进行访问的主要手段,目的是来保证在同一时刻只有一个线程对该对象进行访问。类似于开箱关箱子
golang中提供了一个sync.Mutex类型,并提供了一个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)
}
运行结果:
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
解读:
- 互斥锁需成对出现,可以运用defer防止中间return,忘记写unclock造成死锁。
- 可以验证互斥锁的作用会保护共享资源,使同一时刻只有一个对象访问。