goLang Mutex用法案例详解

Golang以其并发性Goroutines而闻名。不仅是并发,还有更多。

因此,在这种情况下,我们必须确保多个goroutines不应该同时试图修改资源,从而导致冲突。

为了确保资源一次只能被一个goroutine访问,我们可以使用一个叫做sync.Mutex的东西。

This concept is called mutual exclusion, and the conventional name for the data structure that provides it is mutex. — Go dev

无Mutex的用例

让我们有一个简单的用例来理解Mutexgoroutines中的使用。

例如,如果我们需要通过一个goroutine增加一个变量的值,并通过另一个goroutine减少同一个变量的值。

package main

import (
 "fmt"
 "sync"
 "time"
)

func main() {

 const loop = 100
 var wg sync.WaitGroup
 wg.Add(loop * 2)

 // declaring a shared value
 var n int = 0

 for i := 0; i < loop; i++ {
  go func() {
   time.Sleep(time.Second / 10)
   n++
   wg.Done()
  }()
  go func() {
   time.

猜你喜欢

转载自blog.csdn.net/JineD/article/details/129094284