I have multiple goroutines in my program, each of which makes calls to fmt.Println
without any explicit synchronization. Is this safe (i.e., will each line appear separately without data corruption), or do I need to create another goroutine with synchronization specifically to handle printing?
It uses two channels and two Goroutines to control the progress of printing. The first Goroutine is responsible for printing the letters, and the second is responsible for printing the numbers. The first Goroutine will print the letters in order, and the second will print the numbers in order.
Goroutines are incredibly cheap when compared to traditional threads as the overhead of creating a goroutine is very low. Therefore, they are widely used in Go for concurrent programming. To invoke a function as a goroutine, use the go keyword.
A goroutine is a function that executes simultaneously with other goroutines in a program and are lightweight threads managed by Go. A goroutine takes about 2kB of stack space to initialize.
We can add the Goroutine to the Go program by adding the keyword go in front of the function execution. Once we add the go keyword in front of the self-executing function, we are adding concurrency to the execution. Let's see the impact of adding the go keyword to the above execution.
No it's not safe even though you may not sometimes observe any troubles. IIRC, the fmt package tries to be on the safe side, so probably intermixing of some sort may occur but no process crash, hopefully.
This is an instance of a more universal Go documentation rule: Things are not safe for concurrent access unless specified otherwise or where obvious from context.
One can have a safe version of a nice subset of fmt.Print* functionality using the log package with some small initial setup.
Everything fmt
does falls back to w.Write()
as can be seen here. Because there's no locking around it, everything falls back to the implementation of Write()
. As there is still no locking (for Stdout at least), there is no guarantee your output will not be mixed.
I'd recommend using a global log routine.
Furthermore, if you simply want to log data, use the log
package, which locks access to the output properly. See the implementation for reference.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With