相关疑难解决方法(0)

多个goroutines在一个频道上收听

我有多个goroutines尝试同时在同一个频道上接收.似乎在频道上开始接收的最后一个goroutine获得了价值.这是语言规范中的某个地方还是未定义的行为?

c := make(chan string)
for i := 0; i < 5; i++ {
    go func(i int) {
        <-c
        c <- fmt.Sprintf("goroutine %d", i)
    }(i)
}
c <- "hi"
fmt.Println(<-c)
Run Code Online (Sandbox Code Playgroud)

输出:

goroutine 4
Run Code Online (Sandbox Code Playgroud)

在操场上的示例

编辑:

我才意识到这比我想象的要复杂得多.消息在所有goroutine周围传递.

c := make(chan string)
for i := 0; i < 5; i++ {
    go func(i int) {
        msg := <-c
        c <- fmt.Sprintf("%s, hi from %d", msg, i)
    }(i)
}
c <- "original"
fmt.Println(<-c)
Run Code Online (Sandbox Code Playgroud)

输出:

original, hi from 0, hi from 1, hi from …
Run Code Online (Sandbox Code Playgroud)

go

65
推荐指数
4
解决办法
5万
查看次数

多个 goroutine 有选择地在一个通道上监听

我已经看过这个这个这个这个,但在这种情况下没有一个真正帮助我。如果通道中的值是针对该特定 goroutine 的,我有多个 goroutine 需要执行某些任务。

var uuidChan chan string

func handleEntity(entityUuid string) {
    go func() {
        for {
            select {
            case uuid := <-uuidChan:
                if uuid == entityUuid {
                    // logic
                    println(uuid)
                    return
                }
            case <-time.After(time.Second * 5):
                println("Timeout")
                return
            }
        }
    }()
}

func main() {
    uuidChan = make(chan (string))
    for i := 0; i < 5; i++ {
        handleEntity(fmt.Sprintf("%d", i))
    }
    for i := 0; i < 4; i++ { …
Run Code Online (Sandbox Code Playgroud)

channel go goroutine

1
推荐指数
1
解决办法
108
查看次数

标签 统计

go ×2

channel ×1

goroutine ×1