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
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
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")
}
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
main coroutine is blocked, and the pipe is blocked. Only after num++ can be printed. The
pipe is closed with close (pipe name)