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() 释放锁.

相关推荐
牛马喜喜几秒前
记录一次el-table+sortablejs的拖拽bug
前端
一枚前端小能手5 分钟前
⚡ Vite开发体验还能更爽?这些配置你试过吗
前端·vite
Gavin_9155 分钟前
一文速通Ruby语法
开发语言·ruby
搞一搞汽车电子16 分钟前
vs studio 2017项目不支持studio vs2022
开发语言
anyup21 分钟前
🔥 🔥 为什么我建议你使用 uView Pro 来开发 uni-app 项目?
前端·vue.js·uni-app
Skelanimals21 分钟前
Elpis全栈框架开发总结
前端
蓝胖子的小叮当25 分钟前
JavaScript基础(十三)函数柯里化curry
前端·javascript
孪创启航营29 分钟前
数字孪生二维热力图制作,看这篇文章就够了!
前端·three.js·cesium
宫水三叶的刷题日记32 分钟前
真的会玩,钉钉前脚辟谣高管凌晨巡查工位,小编随后深夜发文
前端·后端·面试
witkey_ak989633 分钟前
python 可迭代对象相关知识点
开发语言·python