Check what task finish first in Go?

huangapple go评论79阅读模式
英文:

Check what task finish first in Go?

问题

我想知道是否可以同时运行一个任务(比如一个函数,带有不同的参数,比如int multipliers),并且有一个变量接收第一个完成任务的返回值。有人有什么想法吗? Check what task finish first in 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?
Check what task finish first in Go?

答案1

得分: 1

这是一个基本示例,尽管互联网上还有很多其他示例...

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
}

你可以根据需要扩展这个示例。例如,如果你想要启动任意数量的goroutine N,并且在它们全部完成之前不停止,那么你可以将select语句包装在一个for循环中,并添加一个标志来指示每个goroutine是否已经在其通道上发送了消息。请注意,一个良好设计的程序还应该在另一个方向上进行通信,以便可以关闭你的工作线程。

英文:

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

package main

import &quot;fmt&quot;
import &quot;time&quot;

func main() {
        a := make(chan bool)
        b := make(chan bool)
	go MySleep(5000, a)
	go MySleep(1000, b)
	
	select {
		case _ = &lt;-a:
		     fmt.Println(&quot;a returned first&quot;)
		case _ = &lt;-b:
			fmt.Println(&quot;b returned first&quot;)
	}
}

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.

huangapple
  • 本文由 发表于 2015年6月24日 00:32:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/31008454.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定