Home >Backend Development >Golang >Scheduling strategy of Golang coroutine

Scheduling strategy of Golang coroutine

WBOY
WBOYOriginal
2024-04-15 18:12:021244browse

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.

Scheduling strategy of Golang coroutine

Scheduling strategy of Golang coroutine

Coroutine is a lightweight concurrency mechanism in Go. The scheduling policy determines how coroutine execution is scheduled. Go provides three scheduling strategies:

  • G0
  • G1
  • Non-preemptive scheduling

G0 and G1

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

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.

Practical case

Use G0

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)
    }
}

Use non-preemptive scheduling

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn