对于多个goroutine打印到stdout是否安全?

问题描述:

我的程序中有多个goroutine,每个都调用 fmt.Println ,没有任何明确的同步。这是安全的(即,每行将独立出现没有数据损坏),或者我需要创建另一个goroutine同步专门处理打印?

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?

不,它不安全,即使你有时可能不会观察到任何麻烦。 IIRC,fmt包试图在安全的一面,所以可能会发生某种类型的混合,但没有进程崩溃,希望。

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.

这是一个更多的实例通用Go文档规则:除非另有说明或从上下文显而易见,否则对并发访问不安全。

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.

可以有一个安全版本的fmt.Print *功能使用日志包与一些小的初始设置。

One can have a safe version of a nice subset of fmt.Print* functionality using the log package with some small initial setup.