dongliao1948 2015-06-23 16:32
浏览 5
已采纳

检查Go中首先完成什么任务?

I was wondering if it's possible to do a task (like a function, with different arguments, e.g. int multipliers) run at the same time, and a variable which receive the return value of the first task finished. Someone has any idea? :D

  • 写回答

1条回答 默认 最新

  • dousou3027 2015-06-23 16:53
    关注

    Here is a basic example though there are plenty of others on the internet... https://play.golang.org/p/R__dk09Ymh

    package main
    
    import "fmt"
    import "time"
    
    func main() {
            a := make(chan bool)
            b := make(chan bool)
        go MySleep(5000, a)
        go MySleep(1000, b)
    
        select {
            case _ = <-a:
                 fmt.Println("a returned first")
            case _ = <-b:
                fmt.Println("b returned first")
        }
    }
    
    func MySleep(t int, sig chan bool) {
        time.Sleep(time.Duration(t))
        close(sig)
        return
    }
    

    You can extend this to do whatever you want. For example if you want to spin of some arbitrary number of goroutines N and not stop until they're all complete then you could wrap the select in a for and add a flag to indicate that each goroutine has sent on it's channel. Note that a well made program would also have communication in the other direction so you can shut down your workers.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计
  • ¥15 Arduino无法同时连接多个hx711模块,如何解决?
  • ¥50 需求一个up主付费课程
  • ¥20 模型在y分布之外的数据上预测能力不好如何解决