The documentation for runtime.LockOsThread
states:
LockOSThread wires the calling goroutine to its current operating system thread. Until the calling goroutine exits or calls UnlockOSThread, it will always execute in that thread, and no other goroutine can.
But consider this program:
package main
import (
"fmt"
"runtime"
"time"
)
func main() {
runtime.GOMAXPROCS(1)
runtime.LockOSThread()
go fmt.Println("This shouldn't run")
time.Sleep(1 * time.Second)
}
The main
goroutine is wired to the one available OS thread set by GOMAXPROCS
, so I would expect that the goroutine created on line 3 of main
will not run. But instead the program prints This shouldn't run
, pauses for 1 second, and quits. Why does this happen?
From the runtime
package documentation:
The GOMAXPROCS variable limits the number of operating system threads that can execute user-level Go code simultaneously. There is no limit to the number of threads that can be blocked in system calls on behalf of Go code; those do not count against the GOMAXPROCS limit.
The sleeping thread doesn't count towards the GOMAXPROCS
value of 1, so Go is free to have another thread run the fmt.Println
goroutine.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With