Go 在戈朗卡上了频道

Go 在戈朗卡上了频道,go,channel,goroutine,Go,Channel,Goroutine,我需要并行运行一个函数多次。 如果函数返回true(在通道上发送true),则最终结果应为true 如何使用goroutines和channels实现这一点 // 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()

我需要并行运行一个函数多次。
如果函数返回
true
(在通道上发送
true
),则最终结果应为
true

如何使用goroutines和channels实现这一点

// 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
}
//一些性能密集型函数
func foo(i int,c chan bool){
//进行一些处理并返回true或false

c您可以从通道
ch
开始读取,并在获得真实结果后将
flg
设置为
true
。如下所示:

//flg = flg || <- ch
for res := range ch {
    if res {
        flg = true
    }
}
然后,每次启动goroutine时,您都会向等待组添加一个goroutine:

for i := 0; i < 10; i++ {
    wg.Add(1)   // here
    go foo(i, ch)
}
然后sepate goroutine等待所有foo goroutine退出并关闭通道。
wg.等待
阻塞,直到所有操作完成:

 go func() {
    wg.Wait()
    close(ch)
}()

总之:

您只从通道接收一个值(这将是一个
foo()
调用发送的值,但您希望接收所有值

因此,使用
for
循环接收您发送(发送)的尽可能多的值:


选择此方法时,您应该提供取消goroutines的方法,这些goroutines的工作不再需要,以避免不必要的CPU(和内存)使用。这是否意味着,请在此处详细阅读:。

“如何使用通道实现此目的?”---您为什么必须使用通道?请向我们展示您的尝试。您的代码根本不使用通道。(另外,您最好使用
gofmt
,因为您的代码不容易读写)@zerkms通道是不必要的。只是最初调用foo()是顺序的。现在我想并行运行它们。我想只有goroutine不会有帮助,因为我也需要返回值。欢迎任何其他想法。提前感谢。请在询问之前阅读频道并将相关代码放在这里。Golang tour是一个资源
func foo(i int, c chan bool) {
    //do some processing and return either true or false
    c <- true   //or false
    wg.Done()   // here
}
 go func() {
    wg.Wait()
    close(ch)
}()
for i := 0; i < 10; i++ {
    flg = flg || <-ch
}
ch := make(chan bool, 10)
for i := 0; i < 10; i++ {
    go foo(i, ch)
}

flg := false
for i := 0; i < 10; i++ {
    if <-ch {
        flg = true
        break
    }
}