Question about goroutines

Hi,

I’m new to the go programming language, and I’d like to ask a question about goroutines so I know if understand it well.

Assuming we have one single processor, my understanding is that every cpu bound code inside a goroutine will block the other ones, but if it’s an i/o operation, the code will execute concurrently, so the go runtime won’t wait the i/o operation to finish, and continue the execution of an other goroutine in the meanwhile.

this code work as expected, the go runtime stops the execution of the first goroutine since it’s an i/o operation and execute the second one.
it prints hi then hello
` runtime.GOMAXPROCS(1)

go func() {
	os.Rename("lol", "lollll")
	fmt.Println("hello")
}()

go func() {
	fmt.Println("hi")
}()

time.Sleep(time.Second * 2)`

what i don’t understand is this code

` runtime.GOMAXPROCS(1)

go func() {
	for i := 0; i < 100; i++ {
		fmt.Println("hello")
	}
}()

go func() {
	fmt.Println("hi")
}()

time.Sleep(time.Second * 2)`

it prints all the ‘hello’ and then ‘hi’.
println is not a cpu bound operation, why the go runtime dosen’t stop the first goroutine’s execution and tries to execute the second one ?

Thank you.

Println probably doesn’t result in a blocking syscall so there is no absolute need to switch to a different goroutine. Goroutines can be preempted at any function call (among other conditions), but don’t have to be.

1 Like

Because the first goroutine, which prints “hello” 100 times, is able to execute fully well within the time allocated for it to execute its code before another goroutine is given a chance to execute its code. If you increase the number of iteration such that the iterations may take more time than a typically allocated time slot for a goroutine, then this goroutine will be suspended and the other one will be given its chance to execute. Or, by introducing a sleep between the iterations also you can achieve the switching of the goroutines.

By default, only one Logical processor is used by go runtime and this is bound with only one core of your machine. By instructing the runtime to use more logical processors, i.e., more cores, you can ensure both go routines execute in parallel on different cores, in which case you can expect to see 2 goroutines print “hello” and “hi” in intermixed way

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.