Go study notes - coroutines, channels
1. Coroutine
Go coroutines are lightweight threads of execution.
First define a function f(s)
, using the general form for function calls.
func f(from string) {
for i := 0;i < 3;i++{
fmt.Println(from,":",i)
}
}
func main(){
f("index")
}
//index : 0
//index : 1
//index : 2
The keyword in the Go language go
is used to open goroutine
. All in the same program goroutine
share the same address space.
func f(from string) {
for i := 0;i < 3;i++{
fmt.Println(from,":",i)
}
}
func main(){
f("index")
go f("value")
go func(msg string){
fmt.Println(msg)
}("going")
var input string
fmt.Scanln(&input) // 程序运行结束后,输入任意值结束程序运行
fmt.Println("done")
}
Go's goroutine
is valid until the main function finishes running.
Go coroutines run independently and asynchronously.
func say(s string){
for i:=0;i<5;i++{
time.Sleep(100*time.Millisecond)
fmt.Println(s)
}
}
func main(){
go say("hello goroutine")
say("hello go")
}
//hello goroutine
//hello go
//hello go
//hello goroutine
//hello goroutine
//hello go
//hello go
//hello goroutine
//hello go
According to the output results, it can be seen that the main function ends before the completion of the coroutine, so the data in the coroutine is not completely output. Moreover, the output results are out of order, indicating that the operation of the coroutine is asynchronous.