Home >Backend Development >Golang >Scheduling strategy of Golang coroutine
Go coroutine scheduling has three strategies: G0 and G1: preemptive scheduling, priority G1 > G0. G0 and G1: preemptive scheduling, priority G1 > G0. Non-preemptive scheduling: The coroutine runs until it actively gives up CPU execution rights.
Coroutine is a lightweight concurrency mechanism in Go. The scheduling policy determines how coroutine execution is scheduled. Go provides three scheduling strategies:
G0 and G1 are both preemptive scheduling. This means that a running coroutine can be preempted by a higher priority coroutine.
G1 has a higher priority than G0. If both coroutines are in the runnable state, the G1 coroutine will be executed first.
Non-preemptive scheduling is non-preemptive. This means that running coroutines cannot be preempted. It will continue to run until CPU execution is voluntarily yielded.
package main import ( "fmt" "runtime" "sync" ) func main() { var wg sync.WaitGroup defer wg.Wait() for i := 0; i < 2; i++ { wg.Add(1) go func(i int) { defer wg.Done() fmt.Printf("协程 %d 在 G0 调度器上执行\n", i) runtime.Gosched() }(i) } }
package main import ( "fmt" "runtime" "sync" ) func main() { runtime.LockOSThread() for i := 0; i < 2; i++ { go func(i int) { fmt.Printf("协程 %d 使用非抢占式调度\n", i) }(i) } }
The above is the detailed content of Scheduling strategy of Golang coroutine. For more information, please follow other related articles on the PHP Chinese website!