在fmt.Println调用期间,goroutine可以入睡吗?

I was doing some debugging and had a bit of code like this:

go func() {
        if !finished {
                fmt.Println("Writing the data")
                writer.Write(data)
        }
}()

The finished variable is meant as a guard against writing to a writer that has been closed. However, it wasn't working. It appeared to be getting passed the flag. I determined that the call to Println was yielding the goroutine, which could allow the writer to be closed after checking the flag but before attempting the write. Sure enough, removing the call seems to have fixed it. However, I wanted to verify, and more importantly ask for suggestions on how to avoid this properly, rather than just avoiding prints in there.

Any I/O, yes, including fmt.Println, can cause a pause in goroutine execution.

But in practice, this shouldn't matter, as on any modern hardware, with more than one CPU core, you can experience a race even if the goroutine isn't paused.

You should always make your code concurrency safe.