英文:
Check what task finish first in Go?
问题
我想知道是否可以同时运行一个任务(比如一个函数,带有不同的参数,比如int multipliers),并且有一个变量接收第一个完成任务的返回值。有人有什么想法吗?
英文:
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?
答案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 "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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论