I want to write three concurrent go routines that sends integers to each other. Now, my code is compiled properly, however after first execution it gives error "all goroutines are asleep - deadlock!". I tried to find the error but I could not able to find any error in code logic.Can anybody help me to find the mistake with my code. My code is given below. Thanks in advance.
package main
import "rand"
func Routine1(command12 chan int, response12 chan int, command13 chan int, response13 chan int) {
for i := 0; i < 10; i++ {
y := rand.Intn(10)
if y%2 == 0 {
command12 <- y
}
if y%2 != 0 {
command13 <- y
}
select {
case cmd1 := <-response12:
print(cmd1, " 1st\n")
case cmd2 := <-response13:
print(cmd2, " 1st\n")
}
}
close(command12)
}
func Routine2(command12 chan int, response12 chan int, command23 chan int, response23 chan int) {
for i := 0; i < 10; i++ {
select {
case x, open := <-command12:
{
if !open {
return
}
print(x, " 2nd\n")
}
case x, open := <-response23:
{
if !open {
return
}
print(x, " 2nd\n")
}
}
y := rand.Intn(10)
if y%2 == 0 {
response12 <- y
}
if y%2 != 0 {
command23 <- y
}
}
}
func Routine3(command13 chan int, response13 chan int, command23 chan int, response23 chan int) {
for i := 0; i < 10; i++ {
select {
case x, open := <-command13:
{
if !open {
return
}
print(x, " 2nd\n")
}
case x, open := <-command23:
{
if !open {
return
}
print(x, " 2nd\n")
}
}
y := rand.Intn(10)
if y%2 == 0 {
response13 <- y
}
if y%2 != 0 {
response23 <- y
}
}
}
func main() {
command12 := make(chan int)
response12 := make(chan int)
command13 := make(chan int)
response13 := make(chan int)
command23 := make(chan int)
response23 := make(chan int)
go Routine1(command12, response12, command13, response13)
go Routine2(command12, response12, command23, response23)
Routine3(command13, response13, command23, response23)
}
Can anyone inform me why if I declare Routine2 and Routine3 as go routine, why the output is [no output]. I am new in GO and as per I understood from "http://golang.org/doc/effective_go.html#concurrency", go is used for executing goroutine in parallel with other goroutines in the same address space. So, what is the problem, that all routines are running but output is [no output].
To make program more clear: What actually I am tiring to do is creating two channels between each two routines and then use one channel to send int to other channel and receive int by another channel from that routine. For example between routine 1 & 3 channels are command13 & response13. routine 1 uses command13 to send int and response13 to receive int to/from routine 3.For routine 3 response13 used to send int and command13 to receive int to/from routine 1 (command/response 13 represents channel between routine 1 and 3).Now, as three routines are concurrent and they have specific routines to handle received msg or sending msg, why they go to deadlock ?