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?

- 24,950
- 9
- 62
- 84
-
2It seems it's not totally guaranteed safe : https://groups.google.com/forum/?fromgroups=#!msg/golang-nuts/tUaAOg-vOt4/D1avN9CEw7YJ – Denys Séguret Feb 04 '13 at 19:36
-
Are you using more than one thread? Have you set GOMAXPROCS > 1? – Daniel Feb 04 '13 at 19:36
-
3I have not, but I'd like to know if what I'm doing is threadsafe in the general case. – Taymon Feb 04 '13 at 19:55
3 Answers
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.

- 87,403
- 16
- 175
- 139
-
2
-
3It means you have to setup a new logger instance with the wanted Writer etc. For more info read the docs https://golang.org/pkg/log/#New – Matt Smeets Jul 06 '18 at 06:08
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.

- 55,207
- 13
- 135
- 135
-
Well, it does seem like most things in fmt builds the string in an internal buffer, and call Write() once for each call to fmt.XXX - which will end up in one native write() call, which should be atomic – nos Feb 04 '13 at 20:08
-
There is a buffer object, `pp`, yes. But I don't see where the call to `Write` is locked, which is necessary for this to be thread safe. – nemo Feb 04 '13 at 20:17
-
4@nos, IIUC `write(2)` is only atomic for the amount of bytes the device driver (or the underlying software stack) accepted. I mean, you might need several calls to write all your data, and in this case interleaving might occur naturally. – kostix Feb 05 '13 at 07:44
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)

- 2,343
- 18
- 34