doubi9255
2017-10-14 22:55 浏览 16
已采纳

初学者级代码死锁

here is my main function's body;

c := make(chan int)

go func() {

    i := <-c
    i++
    time.Sleep(100 * time.Millisecond)

    c <-i


}()

time.Sleep(1 * time.Second)
go func() {
    i := <-c
    i++
    time.Sleep(100 * time.Millisecond)
    c <-i

}()

time.Sleep(1 * time.Second)
fmt.Println(<-c)

i am getting deadlock error.even i've tried with waitgroups.hella ripped my hair.

explaining answer would be great for me.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

3条回答 默认 最新

  • 已采纳
    doudao1837 doudao1837 2017-10-15 06:26

    Add before the last line:

    c <- 0
    

    This way you give start value which could be read by goroutines to start working. Also you can add to both goroutines before the last line (sending to channel) add printing goroutine number and value:

    fmt.Println("goroutine 1 value", i)
    

    This you can see how values are passed in situation of 3 possible consumers of the same item in channel. Most likely the main goroutine will read the channel and you get 0. Add Sleep to give others a chance. Play with sleep time toget different results.

    点赞 评论 复制链接分享
  • duanpa1898 duanpa1898 2017-10-14 23:05

    You are reading from the channel before writing to it, so everything deadlocks waiting for a read that can never happen.

    You could break the deadlock by putting c <- 0 before your call to Printf, but the program could then print 0, 1, or 2. Note that if you put the initial send before you start the first goroutine you get the same problem from the other direcion, a send with no possible reads.

    If you said what you were trying to do it would be far easier to help, as it is I can't really provide any specific pointers.

    点赞 评论 复制链接分享
  • dongshi7350 dongshi7350 2017-10-15 23:43

    You Got an Unbuffered channels which means your working "synch" i mean when using an unbuffered channel you need a writer and a reader to achieve something try buffered channels as you can try a select to wait for messages. 2 - you are reading before writing from an unbuffered channel which will block till a write operation happens. so you got 2 readers from a blocked channel ( because there's no writer).

    点赞 评论 复制链接分享

相关推荐