Does runtime.LockOSThread allow child goroutines to run in same OS thread?

后端 未结 2 1097
执念已碎
执念已碎 2021-02-14 09:58

I understand that in Go, runtime.LockOSThread() will bind a goroutine to one OS thread and not allow other goroutines to execute in that thread. Is this also true for child goro

相关标签:
2条回答
  • 2021-02-14 10:14

    We can check it using pthread.h's pthread_self:

    package main
    
    // #include <pthread.h>
    import "C"
    import (
        "fmt"
        "runtime"
    )
    
    func main() {
        runtime.GOMAXPROCS(runtime.NumCPU())
        ch1 := make(chan bool)
        ch2 := make(chan bool)
        fmt.Println("main", C.pthread_self())
        go func() {
            runtime.LockOSThread()
            fmt.Println("locked", C.pthread_self())
            go func() {
                fmt.Println("locked child", C.pthread_self())
                ch1 <- true
            }()
            ch2 <- true
        }()
        <-ch1
        <-ch2
    }
    

    On my machine it prints something like this, main and locked always being sometimes the same, but sometimes different:

    main 139711253194560
    locked 139711219787520
    locked child 139711236572928
    

    EDIT I forgot about GOMAXPROCS. Added, the results are varying now.

    0 讨论(0)
  • 2021-02-14 10:16

    The documentation for runtime.LockOSThread says:

    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.

    (emphasis mine)

    This means that if a certain implementation of Go did what you're asking, it would be faulty.

    To clarify: if a goroutine had reserved a thread and another goroutine executed on that same thread; that's what would be wrong.

    0 讨论(0)
提交回复
热议问题