Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't Go's LockOSThread lock this OS thread?

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?

like image 869
EMBLEM Avatar asked May 25 '16 01:05

EMBLEM


1 Answers

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.

like image 94
user2357112 supports Monica Avatar answered Sep 30 '22 01:09

user2357112 supports Monica