学习笔记,写到哪是哪。
同一时刻只有一个协程可以访问该资源,其他线程只能等待,互斥性。互斥锁在工作项目中用的还是比较多的,但是要注意死锁,也就是一定要注意释放锁的过程是否能够执行。
样例代码如下
package main import ( "fmt" "sync" "time" ) var ( count int myLock sync.Mutex wg1 sync.WaitGroup ) func GetCount() int { myLock.Lock() fmt.Println("GetCount lock ") defer myLock.Unlock() defer fmt.Println("GetCount unlock ") return count } func IncCount() { myLock.Lock() fmt.Println("IncCount lock ") defer myLock.Unlock() defer fmt.Println("IncCount unlock ") count += 1 } func main() { wg1.Add(2) go func() { defer wg1.Done() for i := 0; i < 11; i++ { fmt.Println("count -> ", GetCount()) time.Sleep(1 * time.Second) } }() go func() { defer wg1.Done() for i := 0; i < 10; i++ { IncCount() fmt.Println("count -> add 1") time.Sleep(1 * time.Second) } }() wg1.Wait() }
执行结果
IncCount lock
IncCount unlock
count -> add 1
GetCount lock
GetCount unlock
count -> 1
GetCount lock
GetCount unlock
count -> 1
IncCount lock
IncCount unlock
count -> add 1
IncCount lock
IncCount unlock
count -> add 1
GetCount lock
GetCount unlock
count -> 3
GetCount lock
GetCount unlock
count -> 3
IncCount lock
IncCount unlock
count -> add 1
IncCount lock
IncCount unlock
count -> add 1
GetCount lock
GetCount unlock
count -> 5
GetCount lock
GetCount unlock
count -> 5
IncCount lock
IncCount unlock
count -> add 1
IncCount lock
IncCount unlock
count -> add 1
GetCount lock
GetCount unlock
count -> 7
GetCount lock
GetCount unlock
count -> 7
IncCount lock
IncCount unlock
count -> add 1
IncCount lock
IncCount unlock
count -> add 1
GetCount lock
GetCount unlock
count -> 9
GetCount lock
GetCount unlock
count -> 9
IncCount lock
IncCount unlock
count -> add 1
GetCount lock
GetCount unlock
count -> 10
Process finished with the exit code 0
注意
1、可以看到两个方法在争抢锁,一旦占用,必须要等到释放才可以使用。
2、这里使用了sync.WaitGroup来对协程进行等待。