当我运行我的代码时出现竞争条件。它是并发安全存储的简单实现。当我将 get() 方法中的接收器更改为(p *storageType). 我糊涂了。我需要一个可以向我解释这种行为的人。
package main
type storageType struct {
fc chan func()
value int
}
func newStorage() *storageType {
p := storageType{
fc: make(chan func()),
}
go p.run()
return &p
}
func (p storageType) run() {
for {
(<-p.fc)()
}
}
func (p *storageType) set(s int) {
p.fc <- func() {
p.value = s
}
}
func (p storageType) get() int {
res := make(chan int)
p.fc <- func() {
res <- p.value
}
return <-res …Run Code Online (Sandbox Code Playgroud)