golang 12. goroutine goexit
goroutine.go
package main
import (
"fmt"
"time"
)
//子goroutine
func newTask() {
i := 0
for {
i++
fmt.Printf("new Goroutine : i = %d\n", i)
time.Sleep(1 * time.Second)
}
}
//主goroutine
func main() {
//创建一个go程 去执行newTask() 流程
go newTask()
fmt.Println("main goroutine exit")
i := 0
for {
i++
fmt.Printf("main goroutine: i = %d\n", i)
time.Sleep(1 * time.Second)
}
}
goexit.go
package main
import (
"fmt"
"time"
)
func main() {
//用go创建承载一个形参为空,返回值为空的一个函数
go func() {
defer fmt.Println("A.defer")
func() {
defer fmt.Println("B.defer")
//退出当前goroutine
runtime.Goexit()
fmt.Println("B")
}()
fmt.Println("A")
}()
go func(a int, b int) bool {
fmt.Println("a = ", a, ", b = ", b)
return true
}(10, 20)
//死循环
for {
time.Sleep(1 * time.Second)
}
}
/*
a = 10 , b = 20
B.defer
A.defer
*/