zoukankan      html  css  js  c++  java
  • Wait for a goroutine

    在 Effective Go 中,介绍了一种 goroutine 与 channel 搭配使用的方法。

    package main
    
    import (
    	"fmt"
    	"time"
    )
    
    func main() {
    	c := make(chan string)
    	
    	go func() {
    		time.Sleep(1000)
    		fmt.Println("Go first!")
    		c <- "done"
    	}()
    	
    	fmt.Println("Go after.")
    	fmt.Println("No waiting.")
    	<-c
    	fmt.Println("Wait for the first one.")
    }
    

      

    在这个示例中,使用 go func() {}() 相当于让一段代码在背景执行,我们不用等待它结束就可以继续执行下面的程序,因此,该程序的运行结果是最先打印 "Go after." 

    如果不使用 channel 那么将会在最后才打印 "Go first!"

    这里使用了 channel, 当遇到 <-c 时,程序就会被阻塞,需要等待消息发过来才能继续执行。

    即,在打印完 "No waiting." 之后,等待消息,打印 "Go first!", 发送消息("done"),收到消息,打印 "Wait for the first one."

    也就是说,可以通过使用 channel 来监视 goroutine 有没有结束。

  • 相关阅读:
    每日一题_191208
    每日一题_191207
    每日一题_191206
    每日一题_191205
    每日一题_191204
    每日一题_191203
    每日一题_191202
    每日一题_191201
    每日一题_191130
    2020届成都一诊理科16题
  • 原文地址:https://www.cnblogs.com/ahui2017/p/6662401.html
Copyright © 2011-2022 走看看