小编Mic*_*ael的帖子

如何运行单一实例的goroutine

我有一个将运行多次的 goroutine。但它一次只能运行一个(单个实例)。确保某个 goroutine 一次只能运行一个的正确/惯用方法是什么?

这是我设计的示例代码来说明这一点:

func main() {
    // Contrived example!!!!!!
    // theCaller() may be run at multiple, unpredictable times
    // theJob() must only be run one at a time
    go theCaller()
    go theCaller()
    go theCaller()
}

func theCaller() {
    if !jobIsRunning { // race condition here!
        jobIsRunning = true
        go theJob()
    }
}

var jobIsRunning bool

// Can run multiple times, but only one at a time
func theJob() {
    defer jobDone()
    do_something()
}

func jobDone() {
    jobIsRunning = …
Run Code Online (Sandbox Code Playgroud)

thread-safety go goroutine

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

标签 统计

go ×1

goroutine ×1

thread-safety ×1