对于多个goroutine打印到stdout是否安全? [英] Is it safe for more than one goroutine to print to stdout?

查看:389
本文介绍了对于多个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.

这篇关于对于多个goroutine打印到stdout是否安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆