zoukankan      html  css  js  c++  java
  • [GO]goroutine的使用

    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

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

  • 相关阅读:
    nyoj118 修路工程 次小生成树
    nyoj99 单词连接 欧拉回路
    NYOJ289 苹果 典型背包
    nyoj 139 牌数 康拓展开
    poj1423 NYOJ_69 数字长度 斯特林公式 对数应用
    NYOJ311 完全背包 对照苹果
    sort 函数的应用
    NYOJ120 校园网络 强连接
    nyoj219 计算日期 吉姆拉森公式
    把SmartQ5系统装在SD卡上
  • 原文地址:https://www.cnblogs.com/baylorqu/p/9670148.html
Copyright © 2011-2022 走看看