码迷,mamicode.com
首页 > 其他好文 > 详细

[GO]goroutine的使用

时间:2018-09-18 19:06:00      阅读:154      评论:0      收藏:0      [点我收藏+]

标签:也会   匿名函数   其它   for   break   new   span   class   his   

package main

import (
    "fmt"
    "time"
)

func NewTask()  {
    for true {
        fmt.Println("this is a newtesk goroutine")
        time.Sleep(time.Second) //延时1
    }
}

func main() {

    //一定要写在下面的死循环之前
    go NewTask()//使用go关键字新建一个协程

    for true {
        fmt.Println("this is a main goroutine")
        time.Sleep(time.Second) //延时1
    }
    //NewTask()//如果按照这里的写法,这个方法肯定不会被调用到的
}

执行的结果

this is a main goroutine
this is a newtesk goroutine
this is a newtesk goroutine
this is a main goroutine
this is a main goroutine
this is a newtesk goroutine
this is a main goroutine
this is a newtesk goroutine
this is a main goroutine
this is a newtesk goroutine
///

 这里有一点需要注意的是:在一个程序启动时,其主函数即在一个单独的goroutine中运行,我们叫它main goroutine,新的goroutine会用go语句来创建,当主协程(main goroutine)退出时,其它的子协程也会退出,验证一下

package main

import (
    "fmt"
    "time"
)

func main() {
    go func() {
        i := 0
        for true {
            i ++
            fmt.Println(" 子协程 i = ", i)
            time.Sleep(time.Second)
        }
    }()
    i := 0
    for true {
        i ++
        fmt.Println(" 主协程 i = ", i)
        time.Sleep(time.Second)
        if i == 2{
            break
        }
    }
}

 执行结果

 主协程 i =  1
 子协程 i =  1
 主协程 i =  2
 子协程 i =  2

 被调用的匿名函数是无限循环,当主协程退出时,子协助就算是无限循环也退出了

[GO]goroutine的使用

标签:也会   匿名函数   其它   for   break   new   span   class   his   

原文地址:https://www.cnblogs.com/baylorqu/p/9670148.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!