我有一个将运行多次的 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)