GO教程
GO控制语句
GO高级

Go Mutex

Go Mutex

互斥锁或互斥锁可用于同步对状态的访问并跨多个 goroutine 安全地访问数据。它充当代码临界区入口的守卫,以便一次只有一个线程可以进入临界区。
我们用它为特定的代码行设置了一个锁。当一个 Goroutine 持有锁时,所有其他 Goroutine 都被阻止执行受同一互斥锁保护的任何代码行,并被迫等待直到锁被让出才能继续。
Go互斥体示例
package main
import (
   "sync"
   "time"
   "math/rand"
   "fmt"
)
var wait sync.WaitGroup
var count int
var mutex sync.Mutex
func  increment(s string)  {
   for i :=0;i<10;i++ {
      mutex.Lock()
      x := count
      x++;
      time.Sleep(time.Duration(rand.Intn(10))*time.Millisecond)
      count = x;
      fmt.Println(s, i,"Count: ",count)
      mutex.Unlock()
      
   }
   wait.Done()
   
}
func main(){
   wait.Add(2)
   go increment("foo: ")
   go increment("bar: ")
   wait.Wait()
   fmt.Println("last count value " ,count)
}
输出:
bar:  0 Count:  1
bar:  1 Count:  2
bar:  2 Count:  3
bar:  3 Count:  4
bar:  4 Count:  5
bar:  5 Count:  6
bar:  6 Count:  7
bar:  7 Count:  8
bar:  8 Count:  9
bar:  9 Count:  10
foo:  0 Count:  11
foo:  1 Count:  12
foo:  2 Count:  13
foo:  3 Count:  14
foo:  4 Count:  15
foo:  5 Count:  16
foo:  6 Count:  17
foo:  7 Count:  18
foo:  8 Count:  19
foo:  9 Count:  20
last count value  20

昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4