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

Scheduling strategy of Golang coroutine

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2024-04-15 18:12:02
Original
1325 people have browsed it

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)
    }
}
Copy after login

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)
    }
}
Copy after login

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!

Related labels:
Statement of this Website
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
Latest Issues
How to choose golang web mvc framework
From 1970-01-01 08:00:00
0
0
0
Is it necessary to use nginx when using golang?
From 1970-01-01 08:00:00
0
0
0
golang - vim plug-in to write go
From 1970-01-01 08:00:00
0
0
0
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template