goroutine是什么
goroutine是go并发设计的核心,goroutine说到底其实就是携程,只需要在函数调用语句前添加go关键字,就可创建并发执行单元,开发人员无需了解任何执行细节,调度器会自动将其安排到合适的系统线程上执行。
入门
package main
import (
"fmt"
"time"
)
func newTask(){
fmt.Println("this is a newTask")
time.Sleep(time.Second)
}
func main(){
go newTask() //新建一个携程
for {
fmt.Println("this is a main goroutine")
time.Sleep(time.Second)
}
}
#结果
this is a main goroutine
this is a newTask
this is a main goroutine
this is a main goroutine
主协程退出,子协程一同退出
package main
import (
"fmt"
"time"
)
//主协程退出了,其它子协程也要跟着退出
func main(){
go func(){
i := 0
for {
i++
fmt.Println("子协程 i = ", i)
time.Sleep(time.Second)
if i == 2 {
break
}
}
}()
i := 0
for {
i++
fmt.Println("main i = " , i)
time.Sleep(time.Second)
if i == 2 {
break
}
}
}
#结果
main i = 1
子协程 i = 1
子协程 i = 2
main i = 2
网友评论