当前位置:网站首页>Introduction to goroutine, a high concurrency feature of golang

Introduction to goroutine, a high concurrency feature of golang

2022-07-19 05:56:00 One, two, three

1 golang High concurrency goroutine Introduce

goroutine yes go The core of language high concurrency design , Is a very lightweight implementation , Thousands of concurrent tasks can be performed in a single process , At its core MPG Scheduling model .

1.1 goroutine Principle introduction

Specifically goroutine Before using the method , First introduce its basic principles and related concepts , If you just want to know how to use , Skip directly to the second section .
First of all, introduce the following concept : Concurrent 、 process 、 Thread and Ctrip .

  1. The concept of concurrency
    Long ago , Computers have only one core , The development language metallurgy is to write code logic in sequence , Users can submit one job directly at a time , Computers can only do one thing at a time . But with the development of computer technology , Software design is becoming more and more complex , as well as CPU/ Memory / Hard disk, etc. IO Read and write wait caused by the huge difference in speed , This single process sequential execution , Unable to meet the scenario Application .
    In order to make better use of CPU resources , One CPU Perform multiple tasks at the same time , adopt CPU Time slice polling extreme , Realize the switching between tasks , It looks like multitasking in time , This is concurrency .
    The time-sharing call of computer is the root of concurrency ,CPU Execute different jobs by quickly switching jobs , When each job is blocked during execution , Release CPU resources , Wait until the dispatching unit is awakened again , It can be used again CPU resources , The operating system ensures the whole scheduling process .

  2. process / Threads / Ctrip

A process is an execution of a program in the operating system , An independent unit of the system for resource allocation and scheduling , Process is the smallest unit of computer resource allocation , yes CPU The basic unit of allocation of resources , There is independent memory .
A thread is an execution entity of a process , yes CPU Basic unit of dispatch and dispatch , It's a smaller, independent, basic unit than a process , It is the smallest unit of computer scheduling , A process can have multiple threads
coroutines : Independent stack space , Shared heap space , Scheduling is controlled by the user , It's kind of like a user level thread in essence , The scheduling of these user level threads is also implemented by itself , Its bottom layer is based on thread pool , There is a scheduler on it , On which thread does the scheduling task execute

  1. goroutine principle

goroutine yes golang The process of realization , Its characteristic is that it supports , It is very convenient to use , At its core MPG Scheduling model (M: Kernel thread 、P: processor , Maintain local running queues 、G:goroutine, Code and data structures 、S: Scheduler , maintain M and P)
 principle

M Will associate kernel threads with processes , Context P There are two kinds Goroutine, One is running , Blue in the picture G; One is waiting in line , Gray in the picture G, This will be stored in the process runqueue Inside . The context here P The quantity of also means Goroutinue Number of runs , Through the environment variable GOMAXPROCS Value , Or call the function at run time runtime.GOMAXPROCS() Set it up .

Here is a simple explanation , Specific implementation details , Referable https://zhuanlan.zhihu.com/p/82740001

1.2 goroutine Usage method

golang Used in program go keyword , Add to the front of a function call , You can achieve one goroutine, It's simple , Note here that if you use go establish goroutine when , The return value of the function will be ignored , If you want to realize communication between multiple concurrent ,go Provides channel Mechanism , Very easy to use , It will be introduced separately later .

Use format :
go Function name ( Enter the reference )

Examples are as follows :

package main
 
import (
    "fmt"
    "time"
)
 
func gotest1() {
    i := 0
    for {
        i++
        fmt.Printf("gotest1 run: i = %d\n", i)
        time.Sleep(3*time.Second) // Time delay 1s
    }
}
 
func main() {
    // To start a goroutine
    go gotest1()
    i := 0
    for {
        i++
        fmt.Printf("main: i = %d\n", i)
        time.Sleep(3 * time.Second) // Time delay 1s
    }
}

call runtime.Goexit() The current... Will be terminated immediately goroutine Of board ⾏, The scheduler ensures that all are registered defer Deferred calls are executed .

package main
 
import (
"fmt"
"runtime"
)
 
func main() {
    go func() {
        defer fmt.Println("1111")// Execute when the function exits , amount to c++ Destructor of 
 
        func() {
            defer fmt.Println("2222")
            runtime.Goexit() //  Terminate the current  goroutine
            fmt.Println("3333")
        }()
 
        fmt.Println(44444")
    }()       // How to write anonymous functions 
 
    for {
    }
}

The execution result is
2222
1111

原网站

版权声明
本文为[One, two, three]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/200/202207170509033266.html