Go互斥锁

互斥锁(Mutual Exclusion locks)或称为互斥体(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

标签: Golang, Golang下载, Golang教程, Golang技术, Golang学习, Golang学习教程, Golang语言, Golang开发, Golang入门教程, Golang进阶教程, Golang高级教程, Golang面试题, Golang笔试题, Golang编程思想