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

拈花ヽ惹草 提交于 2019-11-27 14:31:21

问题


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?


回答1:


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.




回答2:


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.




回答3:


The common methods (fmt.printLine) are not safe. However, there are methods that are.

log.Logger is "goroutine safe": https://golang.org/pkg/log/#Logger

Something like this will create a stdout logger that can be used from any go routine safely.

logger := log.New(os.Stdout, "", 0)



来源:https://stackoverflow.com/questions/14694088/is-it-safe-for-more-than-one-goroutine-to-print-to-stdout

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!