Solving goroutines deadlock

前端 未结 5 1938
無奈伤痛
無奈伤痛 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:14

    You need to synchronize all the asynchronous process in your goroutines. Your main thread and the goroutine threads are not synchronous process. Your main thread will never knew when to stop invoking channel from goroutines. Since your main thread loop over the channel, it always invoke the value from channel, and when the goroutines finished and the channel stop sending value, your main thread cannot get anymore value from the channel, hence the condition become deadlock. To avoid this use sync.WaitGroup to synchronize the asynchronous process.

    Here's the code:

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

    https://play.golang.org/p/euMTGTIs83g

    Hope it helps.

    Since my solution looks a little similar to already answered, I change it to my original answer before modification to suit OP question.

    Here's the code:

    package main
    
    import (
        "fmt"
        "time"
        "sync"
    )
    
    // producer produce values tobe sent to consumer
    func producer(ch chan int, d time.Duration, num int, wg *sync.WaitGroup) {
        defer wg.Done();
        for i:=0; i

    Using consumer goroutine to fan-in all input from multiple goroutines and read all values from the consumer goroutine.

    Hope it helps.

提交回复
热议问题