dongxun3777 2016-05-13 12:29
浏览 383

如何避免在此golang程序中出现死锁?

Here is my program which is producing deadlock, how do I avoid it and what is the recommended pattern to handle this kind of situation.

The problem is after timeout how do I detect that there is no reader on my channel ?

var wg sync.WaitGroup

func main() {   
    wg.Add(1)
    c := make(chan int)
    go readFromChannel(c, time.After(time.Duration(2)*time.Second))
    time.Sleep(time.Duration(5) * time.Second)
    c <- 10
    wg.Wait()
}

func readFromChannel(c chan int, ti <-chan time.Time) {
    select {
    case x := <-c:
        fmt.Println("Read", x)
    case <-ti:
        fmt.Println("TIMED OUT")
    }
    wg.Done()
}
  • 写回答

5条回答 默认 最新

  • dongyejun1983 2016-05-13 13:19
    关注

    You have an unbuffered channel. According to the docs:

    If the channel is unbuffered, the sender blocks until the receiver has received the value. If the channel has a buffer, the sender blocks only until the value has been copied to the buffer

    By changing the channel to being buffered, we can avoid deadlock.

    c := make(chan int, 10) // holds 10 ints
    

    I also suggest reading https://golang.org/doc/effective_go.html#channels, it's got some good stuff in there related to channels.

    评论

报告相同问题?

悬赏问题

  • ¥15 yolov8边框坐标
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂