Kadir Susuz
Kadir Susuz

Reputation: 137

deadlock at beginner level code

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.

Upvotes: 0

Views: 66

Answers (3)

Amine Arbi
Amine Arbi

Reputation: 1

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).

Upvotes: 0

Milo Christiansen
Milo Christiansen

Reputation: 3294

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.

Upvotes: 1

Eugene Lisitsky
Eugene Lisitsky

Reputation: 12835

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.

Upvotes: 0

Related Questions