Goroutine channel

I think I need some help to understand channel. In the following code, If I move court <- 1 before the two go routine (go play…) then I get dead lock. I know the unbuffered channel block until the receive and send are ready at the same time. But when I move the court <- 1 before the two goroutines the receiver part are in these two goroutines, I wonder why deadlock results? What’s the difference of putting the court <- 1 before and after the two goroutines? Thanks

package main

import (
	"fmt"
	"math/rand"
	"sync"
	"time"
)

var (
	wg sync.WaitGroup
)
func init(){
	rand.Seed(time.Now().UnixNano())
}

func main(){
	wg.Add(2)
	court := make(chan int)

	go play("James", court)
	go play("Yun", court)

	court <- 1

	wg.Wait()
}

func play(name string, court chan int){
	defer wg.Done()
	for {
		ball, ok := <- court
		if !ok {
			fmt.Printf("player %s won\n", name)
			return
		}
		n := rand.Intn(100)
		if n % 13 == 0{
			fmt.Printf("Player %s missed\n", name)
			close(court)
			return
		}
		fmt.Printf("Player %s Hit %d\n", name, ball)
		court <- ball + 1
	}

}
1 Like

By putting before, you wait for something beeing sent on the channel before starting the go routines, that’s why there is the deadlock.

1 Like

so when I put that after the goroutines, the channel used in goroutines will also block the goroutine as well, correct? this goroutines with channel looks simple but actually I think I still don’t understand how to use it.
should I use the channel with receiving from channel before the channel with sending to channel? or opposite way?
should channel be put after goroutines?

1 Like

Oh, wait, I totally misread your question…

The problem is not that you try to read without data beeing available and therefore block, but its that you are trying to send on an unbuffered channel when actually no receiver is available.

But basically the same effect. Deadlock.

I think I’ll redraw from here, and search myself some bed, before talking even more gibberish…

1 Like

you’re fine @NobbZ and I’m just trying to understand channel in goroutine…

so, looks to me that the unbuffered channel, regardless of sending to channel or receiving from channle, need to start with goroutines before the main function. otherwise there is deadlock. am I correct?

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.