小编Pav*_*vel的帖子

比赛条件。不知道为什么

当我运行我的代码时出现竞争条件。它是并发安全存储的简单实现。当我将 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)

struct pointers go race-condition

1
推荐指数
1
解决办法
63
查看次数

标签 统计

go ×1

pointers ×1

race-condition ×1

struct ×1