Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it safe for more than one goroutine to print to stdout?

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?

like image 498
Taymon Avatar asked Feb 04 '13 19:02

Taymon


People also ask

Can you print Goroutine?

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.

Why is Goroutine used?

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.

What is a Goroutine?

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.

How do you make a Goroutine?

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.


2 Answers

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.

like image 142
zzzz Avatar answered Oct 01 '22 10:10

zzzz


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.

like image 26
nemo Avatar answered Oct 01 '22 08:10

nemo