在使用Mutex时,我注意到了一些意想不到的行为,所以我决定编写一些测试代码。
package main
import (
"fmt"
"sync"
)
type Box struct {
Stuff int
mu sync.Mutex
}
var box Box
func init() {
box = Box{}
box.mu.Lock()
}
func (box *Box) add() {
fmt.Println("add()")
box.mu.Unlock()
box.Stuff++
box.mu.Lock()
}
func (box *Box) display() {
fmt.Print("display(): ")
box.mu.Unlock()
fmt.Println(box.Stuff)
box.mu.Lock()
}
func add2() {
fmt.Println("add2()")
box.Stuff++ //increments but should not, error expected
}
func display2() {
fmt.Print("display2(): ")
fmt.Println(box.Stuff) //displays but should not, error expected
}
func main() {
box.display()
box.add()
box.display()
display2()
add2()
box.display()
}没有指针接收器的函数可以添加和访问受保护的结构。运行代码。
display(): 0
add()
display(): 1
display2(): 1
add2()
display(): 2我希望这两个函数会失败,这两个函数的名称后面加了一个2。他们不知道。
有什么想法吗?
发布于 2022-07-22 22:16:49
您可能想要将它写得有点不同:
您从锁定开始,这并不是使用锁的最常见方式:除非您解除锁定,否则一切都是锁定的。
一个更常见的方法是:
package main
import (
"fmt"
"sync"
)
type Box struct {
Stuff int
mu sync.Mutex
}
var box Box
func init() {
box = Box{}
}
func (box *Box) add() {
fmt.Println("add()")
box.mu.Lock()
box.Stuff++
box.mu.Unlock()
}
...把你的锁范围限定到变化的时刻,而不是整个应用程序。
https://stackoverflow.com/questions/73086397
复制相似问题