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

查看:39
本文介绍了多个 goroutine 打印到标准输出是否安全?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的程序中有多个 goroutine,每个 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 打印到标准输出是否安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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