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

相关推荐
叫我:松哥6 分钟前
基于机器学习的癌症数据分析与预测系统实现,有三种算法,bootstrap前端+flask
前端·python·随机森林·机器学习·数据分析·flask·bootstrap
KookeeyLena87 分钟前
如何限制任何爬虫爬取网站的图片
开发语言·c++·爬虫
让开,我要吃人了9 分钟前
HarmonyOS鸿蒙开发实战(5.0)网格元素拖动交换案例实践
前端·华为·程序员·移动开发·harmonyos·鸿蒙·鸿蒙开发
谢尔登17 分钟前
Webpack 和 Vite 的区别
前端·webpack·node.js
谢尔登17 分钟前
【Webpack】Tree Shaking
前端·webpack·node.js
__AtYou__26 分钟前
Golang | Leetcode Golang题解之第417题太平洋大西洋水流问题
leetcode·golang·题解
yanyanwenmeng27 分钟前
matlab基础
开发语言·算法·matlab
拉玛干33 分钟前
社团周报系统可行性研究-web后端框架对比-springboot,django,gin
数据库·python·spring·golang
过期的H2O233 分钟前
【H2O2|全栈】关于CSS(4)CSS基础(四)
前端·css
末央&43 分钟前
【C++】内存管理
java·开发语言·c++