Go语言现代web开发15 Mutex 互斥锁

Channels are mainly used for goroutines that need to communicate with each other, in order for them to exchange some values. In a situation when multiple goroutines need to update the same value, we must prevent simultaneous access to that value. This concept is known as mutual exclusion.

通道主要用于需要相互通信的程序,以便它们交换一些值。在多个例程需要更新同一值的情况下,必须防止同时访问该值。这个概念被称为互斥。

Why simultaneous access is important? Well, without it, concurrency concepts can be violated. Let us imagine a situation where two goroutines need to duplicate the value of a variable. The initial value of the variable is 5, so the final result should be 20 (5 * 2 * 2).

为什么同时访问很重要? 如果没有它,并发概念就会被违反。让我们想象这样一种情况:两个例程需要复制一个变量的值。变量的初始值是5,所以最终结果应该是20(5 * 2 * 2)。

Without mutual exclusion next scenario is possible. The first goroutne reads the value of variable (5), in the meantime, the second goroutine reads the value of variable (5) and updates the value, so now the value of variable is equal to 10. The first goroutine will now duplicate the value, but it holds the old variable value (5), so the final result will not be 20, it will be 10 which is not crrect.

没有相互排斥,下一种情况是可能的。第一个线程读取变量(5)的值,与此同时,第二个线程读取变量(5)的值并更新该值,因此现在变量的值等于10。第一个例程现在将复制该值,但它保留旧的变量值(5),因此最终结果将不是20,而是10,这是不正确的。

Go programming language provides mutual exclution through the standard library with type Mutex from sync package and two methods: Lock() and Unlock(). Only one goroutine can access code between calls of these two methods at a time. Here is a mutex solution for the previously described problem.

Go编程语言通过sync包中的Mutex类型标准库和Lock()和Unlock()两种方法提供互斥。在调用这两个方法之间,一次只能有一个程序访问代码。下面是前面描述的问题的互斥锁解决方案。

完整代码:

go 复制代码
package main

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

type MutualExclusion struct {
	mutex sync.Mutex
	value int
}

func (me *MutualExclusion) Double() {
	me.mutex.Lock()
	me.value *= 2
	me.mutex.Unlock()
}

func main() {
	me := MutualExclusion{value: 5}
	go me.Double()
	go me.Double()

	time.Sleep(time.Second)
	fmt.Println(me.value)
}

Sleep method is called in order to prevent method Print() to be executed before both goroutines complete execution. If we use the Lock() method to lock a certain part of the code, we must use the Unlock() method to unlock it. If we leave the code locked, other goroutines cannot access them. It is a good practice to combine the all of Unlock() method with defer, so we can be sure that the code will be unlocked no matter what.

调用Sleep方法是为了防止在两个程序完成执行之前执行方法Print()。如果我们使用Lock()方法锁定代码的某个部分,我们必须使用Unlock()方法解锁它。如果我们将代码锁定,其他例程就不能访问它们。将Unlock()方法与defer结合使用是一个很好的做法,这样我们就可以确保代码无论如何都将被解锁。

上面案例的详细中文注释版本:

go 复制代码
package main

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

type MutualExclusion struct {
	mutex sync.Mutex // 互斥锁
	value int        // 要操作的值
}

// Double 定义一个方法,让 value 可以并发的乘以 2
func (me *MutualExclusion) Double() {
	me.mutex.Lock() // 上锁
	me.value *= 2
	me.mutex.Unlock() // 解锁
}

func main() {
	// 在两个 goroutine 中,分别让 value 乘以 2
	// value = 5  ===> 5 x 2 x 2 = 20

	me := MutualExclusion{value: 5}

	// 并发调用,开启两个 goroutine
	go me.Double()
	go me.Double()

	time.Sleep(time.Second) // 让协程能够执行完毕
	fmt.Println(me.value)
}

mutex 的使用建议:

go 复制代码
// Double 定义一个方法,让 value 可以并发的乘以 2
func (me *MutualExclusion) Double() {
	// 最佳实践: 在 lock 之后立马接上 defer unlock
	// 这样,不管我们代码发生什么样的错误,我们始终能够保证锁的安全(上锁,解锁都被执行)
	me.mutex.Lock()         // 上锁
	defer me.mutex.Unlock() // 解锁
	me.value *= 2
}

在上锁以后, 使用 defer mutex.Unlock() 释放锁.

相关推荐
^^为欢几何^^几秒前
npm、pnpm和yarn有什么区别
前端·npm·node.js
布谷歌3 分钟前
Oops! 更改field的数据类型,影响到rabbitmq消费了...(有关于Java序列化)
java·开发语言·分布式·rabbitmq·java-rabbitmq
被程序耽误的胡先生8 分钟前
java中 kafka简单应用
java·开发语言·kafka
刀客1239 分钟前
python小项目编程-中级(1、图像处理)
开发语言·图像处理·python
卷卷的小趴菜学编程13 分钟前
c++之多态
c语言·开发语言·c++·面试·visual studio code
AC-PEACE22 分钟前
Vue 中 MVVM、MVC 和 MVP 模式的区别
前端·vue.js·mvc
播播资源25 分钟前
ChatGPT付费创作系统V3.1.3独立版 WEB端+H5端+小程序端 (DeepSeek高级通道+推理输出格式)安装教程
前端·ai·chatgpt·ai作画·小程序·deepseek·deepseek-v3
冷琴199633 分钟前
基于Python+Vue开发的反诈视频宣传管理系统源代码
开发语言·vue.js·python
楠枬41 分钟前
网页五子棋——对战后端
java·开发语言·spring boot·websocket·spring
kyle~43 分钟前
thread---基本使用和常见错误
开发语言·c++·算法