在Go语言中,互斥锁(Mutex)需要进行初始化吗?

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

Do Mutexes need initialization in Go?

问题

我正在使用Go语言编写一些线程安全的东西。我尝试使用互斥锁。

我在这里找到的示例似乎在没有任何初始化的情况下使用了互斥锁:

...
// 这是被引用页面的关键部分
// (这不是我的代码,我知道这里不需要指针,
// 这是链接中引用网站的代码 - @peterh)

var mutex = &sync.Mutex{}
var readOps uint64 = 0
var writeOps uint64 = 0

for r := 0; r < 100; r++ {
go func() {
total := 0
for {
key := rand.Intn(5)
mutex.Lock()
...

我有点惊讶。他们真的不需要任何初始化吗?

英文:

I am writing some thread-safe thingy in Go. I try to use Mutexes.

The example I've found here, seems to use the Mutexes without any initialization:

...
// essential part of the referred page
// (it is not my code, I know the pointer is unneeded here,
// it is the code of the referred site in the link - @peterh)

var mutex = &amp;sync.Mutex{}
var readOps uint64 = 0
var writeOps uint64 = 0

for r := 0; r &lt; 100; r++ {
    go func() {
        total := 0
        for {
            key := rand.Intn(5)
            mutex.Lock()
....

I am a little bit surprised. Is it real, that they don't need any initialization?

答案1

得分: 30

互斥锁(mutex)不需要初始化。

另外,可以直接使用var mutex sync.Mutex,不需要使用指针。对于整数值,也不需要将它们设置为0,所以你找到的示例可以改进。在所有这些情况下,零值是可以的。

请参考《Effective Go》中的这一部分:

https://golang.org/doc/effective_go.html#data

由于new返回的内存是清零的,因此在设计数据结构时,安排每种类型的零值可以在不进行进一步初始化的情况下使用。这意味着数据结构的用户可以使用new创建一个数据结构并立即开始工作。例如,bytes.Buffer的文档说明“Buffer的零值是一个空缓冲区,可以立即使用”。同样,sync.Mutex没有显式的构造函数或Init方法。相反,sync.Mutex的零值被定义为一个未锁定的互斥锁。

英文:

A mutex does not need initialization.

Also that could just be var mutex sync.Mutex, there's no need for a pointer, same for the int values, there's no need to set them to 0, so that example you found could be improved. In all these cases the zero value is fine.

See this bit of effective go:

https://golang.org/doc/effective_go.html#data

> Since the memory returned by new is zeroed, it's helpful to arrange
> when designing your data structures that the zero value of each type
> can be used without further initialization. This means a user of the
> data structure can create one with new and get right to work. For
> example, the documentation for bytes.Buffer states that "the zero
> value for Buffer is an empty buffer ready to use." Similarly,
> sync.Mutex does not have an explicit constructor or Init method.
> Instead, the zero value for a sync.Mutex is defined to be an unlocked
> mutex.

huangapple
  • 本文由 发表于 2017年8月18日 04:10:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/45744165.html
匿名

发表评论

匿名网友

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

确定