Solving goroutines deadlock

前端 未结 5 1949
無奈伤痛
無奈伤痛 2020-12-18 14:54

I\'ve been trying to solve this simple problem I encountered in Golang concurrency. I\'ve been searching all possible solutions, but found nothing specific to my problem(or

5条回答
  •  渐次进展
    2020-12-18 15:17

    Simpler answer- one of the producers needs to close the channel, and the consumer can just range over the channel.

    package main
    
    import (
        "fmt"
        "time"
    )
    
    func producer(ch chan int, d time.Duration, num int, closer bool) {
    
        for i:=0; i

    Of course, unless you have a situation where you know which producer will always finish last, you would not want to do this in real code. Better designs are in the WaitGroup-based patterns in the other answers. But this is the simplest way for this code to avoid deadlock.

提交回复
热议问题