Go - Mutex

Go - Mutex 首页 / Golang入门教程 / Go - Mutex

互斥锁或互斥锁可用于同步对状态的访问,并跨许多goroutine安全地访问数据。它充当代码关键部分入口的保护,因此一次只能有一个线程进入。

我们用它在特定代码行周围设置了锁。当一个Goroutine持有锁时,所有其他Goroutine均被阻止执行受同一互斥锁保护的任何代码行,并被迫等待直到产生锁之后才能继续执行。

Mutex示例

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

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

深入拆解Java虚拟机 -〔郑雨迪〕

系统性能调优必知必会 -〔陶辉〕

打造爆款短视频 -〔周维〕

性能优化高手课 -〔尉刚强〕

Redis源码剖析与实战 -〔蒋德钧〕

手把手带你搭建秒杀系统 -〔佘志东〕

业务开发算法50讲 -〔黄清昊〕

人人都用得上的数字化思维课 -〔付晓岩〕

Vue 3 企业级项目实战课 -〔杨文坚〕

好记忆不如烂笔头。留下您的足迹吧 :)