Go scheduler and CGO: Please explain this difference of behavior?

后端 未结 1 1802
别那么骄傲
别那么骄傲 2021-01-16 11:27

I\'d like to know the implementation reason for this:

package main

func main() {
    c := make(chan struct{})

    go func() {
        print(\"a\")
                 


        
相关标签:
1条回答
  • 2021-01-16 11:44

    The runtime can't preempt a true busy-loop. A CPU intensive loop with no scheduling points has to be in it's own thread for other goroutines to be able to run. Function calls and channel send or receive operations all yield. Network IO is scheduled asynchronously, and file IO gets its own thread.

    Generally setting GOMAXPROCS > 1 is sufficient, but since you have 3 of these loops, and only 2 threads, the scheduler is still blocked. If you have a valid CPU intensive loop that is making it difficult to schedule goroutines, you can call runtime.GoSched() periodically to yield to the scheduler. In the real world, the only place where this generally maters is a programming error where you have an empty loop.

    All cgo calls happen in their own threads outside of the go runtime, so those loops have no effect on the main loop, other than wasting CPU.

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