I have a race condition that is clearly real. I don't think it will cause a problem, but I wanted to make sure I'm not missing something non-obvious, either in a side-effect or in a better way to do it.
Below is a stripped down toy version of what I'm working with, I also have it in the playground. The race condition output is below the code listing.
Basically, I'm swapping out a func in a var to turn debug output on/off. My thoughts are that the assignment is "atomic" and thus I'm not at risk for unexpected behavior. I realize I could embed it in a struct with appropriate methods and a lock, but I like having it behave as a straight func.
(obviously running it in the playground won't show the -race output)
It's a go routine printing debug output and a main routine turning the debug on and off.
Is there something bad possibly happening that I'm missing or a better way to do this. I also like having clean -race output.
Thanks!
package main
import (
"fmt"
"time"
)
func DebugOn(fmtstr string, args ...interface{}) {
fmt.Printf(fmtstr, args...)
return
}
func DebugOff(fmtstr string, args ...interface{}) {
return
}
var Debug = DebugOn
func main() {
go func() {
for i := 1; i <= 100; i++ {
Debug("%03d: Debug\n", i)
time.Sleep(100 * time.Millisecond)
}
}()
for i := 1; i <= 5; i++ {
time.Sleep(1 * time.Second)
Debug = DebugOff
time.Sleep(1 * time.Second)
Debug = DebugOn
}
return
}
/*
==================
WARNING: DATA RACE
Write by main goroutine:
main.main()
/emu/build/art/repo/Go/src/race/race.go:30 +0x6c
Previous read by goroutine 5:
main.func-001()
/emu/build/art/repo/Go/src/race/race.go:23 +0xf1
Goroutine 5 (running) created at:
main.main()
/emu/build/art/repo/Go/src/race/race.go:26 +0x37
==================
*/