Go language --- concurrent programming goroutine

Concurrency in Go language is achieved through goroutine. A goroutine is similar to a thread and belongs to a user mode thread. Go language can also communicate with multiple goroutines through channels.

goroutine

A goroutine is similar to a thread. A thread pool is allocated at the bottom of the Go language, so we don't need to manage it, and it is scheduled by the routine of the Go runtime.
It is very simple to implement a goroutine in the Go language. You only need to add the go keyword before calling the function to create a goroutine for the function. Therefore, one goroutine corresponds to one function, and multiple goroutines can correspond to multiple functions.

//串行执行
package main

import "fmt"

func hello(){
    
    
	fmt.Println("Hello")
}

func main(){
    
    
	hello()
	fmt.Println("Hello Main")
}

The above code is executed serially. After executing a function, the next statement will be executed. If you want it to be executed concurrently, you need a goroutine

func main(){
    
    
	go hello()
	fmt.Println("Hello Main")
}

Just add a go keyword when calling a specific function.
Insert picture description here
After adding the keyword, when calling a specific method, the main thread does not need to call, the main thread will continue to execute, and the main thread executes concurrently with the child threads. Therefore, the execution results are different.
Insert picture description here
If you want all the execution to end, then return.

func main(){
    
    
	go hello()
	fmt.Println("Hello Main")
	time.Sleep(10)	//等待10ns,但是效率低
} 

Insert picture description here
Common methods:

package main

import (
	"fmt"
	"sync"
)
var Sy sync.WaitGroup

func hello(){
    
    
	fmt.Println("Hello")
	Sy.Done() //计数器-1
}

func main(){
    
    
	Sy.Add(1) //计数器+1
	go hello()
	fmt.Println("Hello Main")
	Sy.Wait() //等待计数器==0的时候直接退出
} 

At the same time, goroutines can also use anonymous functions, but when anonymous functions are used again, it is easy to cause closure problems, which requires attention.

GOMAXPROCS sets the number of CPU cores used

Before Go1.5 version, single-core operation was used by default. After version 1.5, all CPU cores are used by default for operation, which can make full use of hardware resources.

//使用方法
runtine.GOMAXPROCS(核心数)
package main

import (
	"fmt"
	"sync"
	"runtime"
)

var wg sync.WaitGroup

func hello(){
    
    
	fmt.Println("Hello")
	wg.Done()
}

func helloWorld(){
    
    
	fmt.Println("HelloWorld")
	wg.Done()
}

func main(){
    
    
	runtime.GOMAXPROCS(4)   
	wg.Add(2) //计数器+2
	go hello()
	go helloWorld()

	wg.Wait()	
} 

One operating system thread corresponds to multiple user mode goroutines
Go language programs can use multiple operating system threads at the same time
There is a many-to-many relationship between goroutine and OS threads

Guess you like

Origin blog.csdn.net/qq_42708024/article/details/107299161