Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"all goroutines are asleep - deadlock! Exit status 2" error in a printer-receiver program

Tags:

go

channel

I am trying to create a simple program to learn channels in Go. But I´m running in to a deadlock error, which I can´t figure out

package main

import (
    "fmt"
    "time"
)

func printer(c chan int) {
    for i := 0; i < 10; i++ {
        c <- i
        time.Sleep(time.Second)
    }
}

func reciever(c chan int) {
    for {
        recievedMsg := <-c
        fmt.Println(recievedMsg)
    }
}

func main() {
    newChanel := make(chan int)
    printer(newChanel)
    reciever(newChanel)
}

My initial thoughts was something about the Sleep function, but even if I don´t include this I still run into this error and exit message. Can anyone give some hints on how to solve this?

Thanks in advance

like image 592
miner Avatar asked Sep 12 '12 15:09

miner


1 Answers

You need two execution threads because now there is no way for the reciever function to be called as you never leave the printer function. You need to execute one of them on a separate goroutine.

You should also close the channel and use the range operator in your loop, so that it ends when the channel is closed.

So I propose you this code :

func printer(c chan int) {
    for i := 0; i < 10; i++ {
        c <- i
        time.Sleep(time.Second)
    }
    close(c)
}

func reciever(c chan int) {
    for recievedMsg := range c {
        fmt.Println(recievedMsg)
    }
}

func main() {
    newChanel := make(chan int)
    go printer(newChanel)
    reciever(newChanel)
}
like image 113
Denys Séguret Avatar answered Oct 20 '22 03:10

Denys Séguret