英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论