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

相关推荐
恋猫de小郭2 分钟前
为什么跨平台框架可以适配鸿蒙,它们的技术原理是什么?
android·前端·flutter
云浪5 分钟前
元素变形记:CSS 缩放函数全指南
前端·css
明似水21 分钟前
用 Melos 解决 Flutter Monorepo 的依赖冲突:一个真实案例
前端·javascript·flutter
钮钴禄·爱因斯晨30 分钟前
Java 面向对象进阶之多态:从概念到实践的深度解析
java·开发语言·数据结构
鸽子炖汤30 分钟前
Java中==和equals的区别
java·开发语言·jvm
独立开阀者_FwtCoder30 分钟前
stagewise:让AI与代码编辑器无缝连接
前端·javascript·github
清沫32 分钟前
Cursor Rules 开发实践指南
前端·ai编程·cursor
有个傻瓜34 分钟前
PHP语言核心技术全景解析
开发语言·kubernetes·php
江城开朗的豌豆38 分钟前
JavaScript篇:对象派 vs 过程派:编程江湖的两种武功心法
前端·javascript·面试
不吃糖葫芦339 分钟前
App使用webview套壳引入h5(二)—— app内访问h5,顶部被手机顶部菜单遮挡问题,保留顶部安全距离
前端·webview