Code snippet below,
package main
import (
"fmt"
"runtime"
)
func main() {
runtime.GOMAXPROCS(1)
var s string
done := make(chan bool)
go func() {
fmt.Scanln(&s)
fmt.Println(s)
done <- true
}()
var i int
for i = 0; i < 1e10; i++ {
}
fmt.Println(i)
<-done
}
Run it, quickly type a few chars e.g. abcd
before the for
loop ends; finally hit Enter
. To my knowledge there is none of yield points available within the for
loop for Gosched
to switch the main goroutine to the subroutine, why had it promptly printed abcd
even before the for
loop was finished?
abcd10000000000
abcd
It is random you cannot predict the output. Because in your case the go routine will run and then the for loop will execute. Now if go routine finished before the for loop completes its iterations then it will print the value inside the go routine first and send the value on done
channel and then it will print the value of i
. The done
channel will wait until the value is sent on it by the go routine.
For example if you try to scan only as
and then enter fast your value will print first inside the go routine then 10000000000
will print in the last so it depends on if go routine will execute before the for loop completes.
The runtime can allocate more threads than the value of GOMAXPROCS
to service multiple outstanding I/O requests. GOMAXPROCS
only affects how many goroutines can actually execute at once; arbitrarily more may be blocked in system calls.
Code runs as expected,
Every running program have got access to three files,stdin
, stdout
, stderr
.
Anything you type in your terminal, is you writing to stdin
file, and programs output is written to stdout
.
In your case, you have written some data to stdin
, which is being read and displayed.
In case you have written some data before even the process starts processing your input, it's the same thing, reading from file.
Basically when ever the program starts and get's enough input it proceeds, if it didn't get chance to execute, until someone reads input it's in stdin
still.
Since GOMAXPROCS
doesn't mean that you are going to run only one goroutine, if that is blocked a new one is created. GOMAXPROCS
implies at any instance of time only one user thread can be running.