我在Go中写了一些线程安全的东西.我尝试使用互斥锁.
我在这里找到的例子,似乎没有任何初始化使用互斥锁:
...
// 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 = &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()
....
Run Code Online (Sandbox Code Playgroud)
我有点惊讶.这是真的吗,他们不需要任何初始化?
Ken*_*ant 12
互斥锁不需要初始化.
另外,这可能只是var mutex sync.Mutex,不需要指针,对于int值也是如此,不需要将它们设置为0,因此您找到的示例可以得到改进.在所有这些情况下,零值都很好.
看到这一点有效的去:
https://golang.org/doc/effective_go.html#data
由于new返回的内存归零,因此在设计数据结构时安排每个类型的零值可以在不进一步初始化的情况下使用是有帮助的.这意味着数据结构的用户可以使用new创建一个并获得正常工作.例如,bytes.Buffer的文档声明"Buffer的零值是一个可以使用的空缓冲区".同样,sync.Mutex没有显式构造函数或Init方法.相反,sync.Mutex的零值被定义为未锁定的互斥锁.