go语言中的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的用例

让我们有一个简单的用例来理解Mutex在goroutines中的使用。
例如,如果我们需要通过一个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.Sleep(time.Second / 10)
			n--
			wg.Done()
		}()
	}
	wg.Wait()
	// printing the final value of n
	if n != 0 {
   
		fmt.Println("The Final value of n should be 0. But found ", n)
		return
	}
	fmt.Printf("\nFinal value of n is %d\n\n", n) // the final of n should be 0
}

在这个循环中,我使用了两个带有goroutines的匿名函数。一个将增加n的值,另一个将减少n的值。在最后,n的值应该是0,因为初始值是0,对于每个循环计数,我都是先增后减,所以在最后应该和初始值一样。但如果不使用Mutex,情况就不是我们所期望的那样了。
在上述输出中,我们可以看到结果不是恒定的。

我们可以使用go run命令中的-race来检测是否存在数据竞赛。

数据竞赛发生在:一个进程中的两个或多个线程同时访问同一个内存位置。

sync.Mutex

它拥有两个方法:

  • Lock
  • Unlock
    使用Lock来锁定资源,以便每次只有一个goroutine可以访问该资源。

Unlock用于解锁被锁住的资源。

使用Mutex也有同样的用例。

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
	var m sync.Mutex

	for i := 0; i < loop; i++ {
   
		go func() {
   
			time.Sleep(time.Second / 10)
			m.Lock() // locking the resource n
			n++
			m.Unlock() // unlocking the resource n
			wg.Done()
		}()
		go func() {
   
			time.Sleep(time.Second / 10)
			m.Lock() // locking the resource n
			n--
			m.Unlock() // unlocking the resource n
			wg.Done()
		}()
	}
	wg.Wait()
	// printing the final value of n
	if n != 0 {
   
		fmt.Println("The Final value of n should be 0. But found ", n)
		return
	}
	fmt.Printf("\nFinal value of n is %d\n\n", n) // the final of n should be 0
}

在这里,两个goroutine试图同时访问同一个资源n。但在Mutex.Lock()的帮助下,我们可以锁定该资源,这样它就只能被一个goroutine使用。

在上面的输出中,我们可以看到,输出总是0(正如我们所期望的)。

我们也可以在使用Mutex的时候检查数据竞赛。

我们可以清楚地看到,在使用Mutex时没有数据竞赛。

另外,我们可以对资源Unlock()使用defer语句,所以它将在被锁定的块的末尾被解锁。

go func() {
   
		time.Sleep(time.Second / 10)
		m.Lock() // locking the resource n
		n--
		m.Unlock() // unlocking the resource n
		wg.Done()
}()

相关推荐

  1. go语言Mutex

    2024-01-30 16:02:01       49 阅读
  2. Go 语言互斥锁 Mutex

    2024-01-30 16:02:01       32 阅读
  3. go 语言 iota

    2024-01-30 16:02:01       53 阅读
  4. go语言GoMock

    2024-01-30 16:02:01       45 阅读
  5. Go语言Pool

    2024-01-30 16:02:01       56 阅读
  6. Go语言Channel

    2024-01-30 16:02:01       52 阅读
  7. Go 语言 Map

    2024-01-30 16:02:01       36 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-01-30 16:02:01       98 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-01-30 16:02:01       106 阅读
  3. 在Django里面运行非项目文件

    2024-01-30 16:02:01       87 阅读
  4. Python语言-面向对象

    2024-01-30 16:02:01       96 阅读

热门阅读

  1. Docker

    Docker

    2024-01-30 16:02:01      50 阅读
  2. Qt Bezier闭合曲线插值(2D)

    2024-01-30 16:02:01       53 阅读
  3. FreeRTOS简介

    2024-01-30 16:02:01       64 阅读
  4. HTML5 服务器发送事件(Server-Sent Events)

    2024-01-30 16:02:01       61 阅读
  5. JNDI以及利用JNDI进行漏洞攻击

    2024-01-30 16:02:01       55 阅读
  6. 【Vue】为什么Vue3使用Proxy代替defineProperty?

    2024-01-30 16:02:01       55 阅读
  7. Hotspot源码解析-第28章-终结篇章

    2024-01-30 16:02:01       50 阅读
  8. 在Ubuntu环境下搭建小型化Git服务器

    2024-01-30 16:02:01       45 阅读
  9. 隐马尔可夫模型系列——(三)模型推断

    2024-01-30 16:02:01       51 阅读