我需要通过创建x0个Goroutine来增加xx0倍,这将通过通道增加x个.我该怎么做呢?

package main

import (
    "fmt"
)

func main() {
    var ch = make(chan int)

    //1000 goroutines sending 1 through a channel
    var x = 0
    for i := 0; i < 1000; i++ {
        go func() {
            ch <- 1
        }()
    }

    //Here i need to increase x by value read from the channel and then stop when the last value was sent
    //But this code doesn't work
    for {
        if v, ok := <-ch; ok {
            x += v
        } else {
            break
        }
    }

    fmt.Println(x)
}

我想在最后关闭通道,但我不知道如何检测最后一个值是什么时候发送的

推荐答案

sync.WaitGroup可用于检测一组Goroutine的完成情况.例如:

package main

import (
    "fmt"
    "sync"
)

func main() {
    var ch = make(chan int)
    wg := &sync.WaitGroup{}

    //1000 goroutines sending 1 through a channel
    var x = 0
    for i := 0; i < 1000; i++ {
        wg.Add(1)
        go func() {
            defer wg.Done()
            ch <- 1
        }()
    }

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

    //Here i need to increase x by value read from the channel and then stop when the last value was sent
    //But this code doesn't work
    for {
        if v, ok := <-ch; ok {
            x += v
        } else {
            break
        }
    }

    fmt.Println(x)
}

Go相关问答推荐

VS代码,Golang格式顽固的情况与switch / case

如何使用Docker Compose配置Go,使main. go文件位于/CMD文件夹中

正在使用terratest执行terraform脚本测试,但遇到错误退出状态1

理解Golang并发:缓冲通道的意外行为

Golang Viper:如果第一个字段不存在,如何从另一个字段获取值

有没有办法通过Go cmdline或IDE(IntelliJ)找出我的 struct 实现了什么接口?

Websocket服务器实现与x/net库trowing 403

golang testscript .txtar 语法,用于 stderr 或 stdout 中包含的文本

使用golang sqlc中的引用参数

golang / urfave.cli:无法手动设置标志

Go Programming Language书上的例子server2错了吗?

Go 的垃圾收集器在使用时删除 ZeroMQ 套接字

具有未导出字段的 struct 类型之间的转换

io.Pipe 使用困难

go:识别重新定义标志的包

自定义指标未显示在 prometheus web ui 中,grafana 中也是如此

如果服务器在客户端的 gRPC 中不可用,则等待的方法

如何排除溢出矩阵的坐标

在 Go 中,为什么 exec.Command() 失败但 os.StartProcess() 成功启动winget.exe?

AWS EKS 上的 Golang REST API 部署因 CrashLoopBackOff 而失败