【发布时间】:2017-10-06 09:36:38
【问题描述】:
我需要并行运行一个函数。
如果即使函数返回true(在频道上发送true),那么最终结果应该是true。
如何使用 goroutine 和通道实现这一点?
// Some performance intensive function
func foo(i int, c chan bool) {
// do some processing and return either true or false
c <- true // or false
}
func main() {
flg := false
ch := make(chan bool)
for i := 0; i < 10; i++ {
go foo(i, ch)
}
// If even once foo() returned true then val should be true
flg = flg || <-ch
}
【问题讨论】:
-
"如何使用渠道实现这一目标?" --- 有什么理由必须为此使用频道?
-
请向我们展示您的尝试。您的代码根本不使用频道。
-
(另外,建议您使用
gofmt,因为您的代码不易阅读) -
@zerkms 频道不是必需的。只是最初对 foo() 的调用是连续的。现在我想并行运行它们。我认为只有 goroutine 无济于事,因为我也需要返回值。欢迎任何其他想法。提前致谢。
-
请在询问之前阅读频道并将相关代码放在这里。 Golang 之旅是一种资源tour.golang.org/concurrency/2