Home  >  Article  >  Backend Development  >  How to start coroutine in golang

How to start coroutine in golang

(*-*)浩
(*-*)浩Original
2019-12-30 15:51:063419browse

How to start coroutine in golang

Essentially, goroutine is a coroutine. The difference is that Golang encapsulates and processes goroutine scheduling in many aspects such as runtime and system calls. When encountering long-term execution or system calls. (Recommended learning: go)

will actively transfer the CPU (P) of the current goroutine so that other goroutines can be scheduled and executed. That is, Golang supports coroutines from the language level. .

One of the major features of Golang is that it natively supports coroutines from the language level. You can create a coroutine by adding the go keyword in front of a function or method.

Comparison of other aspects

Memory consumption

Each goroutine (coroutine) occupies memory by default There are far fewer threads than Java and C.

goroutine: 2KB

Thread: 8MB

Thread and goroutine switching scheduling overhead

Thread/goroutine switching overhead, Goroutine is far smaller than threads

Threads: involve mode switching (switching from user mode to kernel mode), 16 registers, PC, SP... and other register refreshes, etc.

goroutine: only three register value modifications - PC/SP/DX.

We know that coroutine (coroutine) is a lightweight thread implementation in the Go language. Managed by the Go runtime.

Add the go keyword before a function call, and the call will be executed concurrently in a new goroutine. When the called function returns, this goroutine also ends automatically. It should be noted that if this function has a return value, the return value will be discarded.

First look at the following program code:

func Add(x, y int) {
    z := x + y
    fmt.Println(z)
}
func main() {
    for i:=0; i<10; i++ {
        go Add(i, i)
    }
}

When you execute the above code, you will find that nothing is printed on the screen and the program exits.

The above is the detailed content of How to start coroutine in golang. 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