将sync.Mutex放置在包级变量中是否会对包级映射产生任何影响?

huangapple go评论80阅读模式
英文:

Does placing sync.Mutex in package level variable has any effects on package level maps?

问题

在以下函数中调用mu.Lock()会锁定包级别的accCache映射:

package cache

import (
	"sync"
)

type CachedAccount struct {
	Id       string
	Expires  int64
}


var accCache = make(map[string]CachedAccount)

var mu sync.Mutex


func addAccount...
func getAccount...

请注意,这只是一个代码片段,缺少函数的具体实现。要确保在访问或修改accCache映射时使用mu.Lock()mu.Unlock()来保证并发安全性。

英文:

Would calling mu.Lock() in one of the following functions lock the package level accCache map?

package cache

import (
	"sync"
)

type CachedAccount struct {
	Id       string
	Expires  int64
}


var accCache = make(map[string]CachedAccount)

var mu sync.Mutex


func addAccount...
func getAccount...

答案1

得分: 5

调用sync.Mutex类型变量的Lock方法除了确保任何其他调用相同变量的Lock方法的goroutine将暂停执行,直到其他goroutine在同一变量上调用Unlock方法之外,不会有任何其他操作。

也就是说,你的思路是错误的:互斥锁本身并不保护任何程序状态。相反,它只是一种明确序列化访问程序某些部分状态的手段。
哪些部分是由访问它们的代码决定的,所有这些代码都应该使用一些约定的机制来序列化这种访问(可以是互斥锁或其他东西)。

正因为如此,代码中可能会引入数据竞争:如果不是所有访问程序相同部分状态的代码路径都使用相同的同步机制,就会存在数据竞争条件。

英文:

Calling Lock on a variable of type sync.Mutex does nothing except for ensuring that any other goroutine which calls Lock on the same variable will suspend its execution until some other goroutine calls Unlock on that same variable.

That is, your line of thinking is wrong: a mutex does not by itself protect any program state. Instead, it's only a certain means of explicitly serializing access to some parts of the program's state.
Which parts are these—is decided by which code accesses them, and all that code should use some agreed-upon mechanism of serializing such access (it can be a mutex or something else).

Specifically because of this, it's possible to introduce data races in the code: if not all code paths which access the same parts of the program's state use the same synchronization mechanisms, a data race condition exists.

huangapple
  • 本文由 发表于 2021年10月19日 23:13:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/69633461.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定