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

前端 未结 3 1387
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-09 08:39

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 appe

3条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-09 09:15

    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.

提交回复
热议问题