Multithreaded console output?

If I have multiple running procedures and 2 or more of them decide they need to print something, is it possible for them to interrupt each other?

For example:

package main

import (
    "fmt"
)

func main() {
    go print()
    print()
}

func print() {
    for true {
        fmt.Print("ABCDEF")
    }
}

      

Is it possible for one call program to start printing ( AB

) and another interrupt routine ( ABABCDEF

) and initial termination ( ABABCDEFCDEF

)?

I tried to run it myself and check the output and it looks good, but how can I be sure?

+3


source to share


1 answer


Yes, it is possible, although you won't see anything with GOMAXPROCS = 1. They will show up when working with a lot of goroutines, large lines, and a lot of threads. Even more so when writing to stderr, which is unbuffered, since the stdout buffer accepts short writes fast enough to prevent interleaving.



This is why the Logger in the "log" package has an internal mutex and buffer to properly serialize calls.

+4


source







All Articles