GO summary of six coroutines

1 Introduction

A more lightweight parallel method than threads. GO supports this operation from the language level

Use of two coroutines

It is very simple to use, just use the keyword go to identify it, and it will automatically open a coroutine to execute

package main

import (
	"fmt"
	"time"
)

func show(){

	fmt.Println("go")

}

func main() {//g语言中的 ‘{’ 不能独占一行

	go show()
	time.Sleep(time.Second)//延时一秒
	fmt.Println("main")
}

Result
Insert picture description here
Note that after the main coroutine exits, the sub coroutines will also exit

Three Gosched

Give up the time slice, and other coroutines will execute first

package main

import (
	"fmt"
	"runtime"
)

func show(){

	fmt.Println("go")

}


func main() {//g语言中的 ‘{’ 不能独占一行

	go show()
	runtime.Gosched()
	fmt.Println("main")
}

result
Insert picture description here

Four Goexit

End coroutine

package main

import (
	"fmt"
	"runtime"
)

func show(){

	runtime.Goexit()
	fmt.Println("go")

}


func main() {//g语言中的 ‘{’ 不能独占一行

	go show()
	runtime.Gosched()
	fmt.Println("main")
}

Insert picture description here

Five pipelines

Can be used for coroutine synchronization

package main

import (
	"fmt"
)

var ch1 = make(chan int)
//创建全局channel

var num int = 0
func show(){
	<-ch1//当管道没有数据,会阻塞在这一步
	fmt.Println("num=",num)
}

func add(){
	num++
	ch1<-9
}


func main() {//g语言中的 ‘{’ 不能独占一行

	go add()
	go show()
	for{//主协程阻塞

	}
}


Results The
Insert picture description here
main coroutine is blocked, and the pipe is blocked. Only after num++ can be printed. The
pipe is closed with close (pipe name)

Guess you like

Origin blog.csdn.net/GreedySnaker/article/details/114451635