I have a goroutine that will be run multiple times. But it can only run one at a time (single instance). What is the correct/idiomatic way to make sure a certain goroutine can run only one at a time?
Here is my contrived example code to illustrate the point:
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 = false
}