How to use a CHANNEL? Golang always tell me throw: all goroutines are asleep - deadlock!

2,626 views
Skip to first unread message

feeling4t

unread,
Jul 23, 2012, 10:42:56 PM7/23/12
to golan...@googlegroups.com
Hi guys, I'm really new in golang

when I try this code:

func main(){
ch := make(chan int)
ch <- 2
i :=<- ch
fmt.Printf("%d",i)
}

the golang always tell me

throw: all goroutines are asleep - deadlock!

goroutine 1 [chan send]:
main.main()
/home/feeling4t/workspace/routetest/src/main.go:16 +0x51

goroutine 2 [syscall]:
created by runtime.main
/tmp/bindist046461602/go/src/pkg/runtime/proc.c:221

I think the way I use channel must be wrong, could any one tell me why?
Thanks
Message has been deleted

Daniël Bos (远洋)

unread,
Jul 23, 2012, 11:50:54 PM7/23/12
to feeling4t, golan...@googlegroups.com
As Peter Russell already mentioned, the channel you are using is
unbuffered, so since no-one is listening at the moment when you write
to the channel, the call will block.

Usually channels are used to communicate between different threads of
operation (go-routines), you could use it like this:

func main(){
ch := make(chan int)
go func() { ch <- 2 }()
i :=<- ch
fmt.Printf("%d",i)
}

This will create an anonymous function that will write to the channel,
and execute it in a separate thread. Because this runs in parallel,
the following line, where you read from the channel, is reached, which
will un-block the writer, and all is well.

You can play with it here: http://play.golang.org/p/macbX7u2up

--
远洋 / Daniël Bos

feeling4t

unread,
Jul 24, 2012, 1:50:39 AM7/24/12
to golan...@googlegroups.com
It did works
Thanks

在 2012年7月24日星期二UTC+8上午11时24分07秒,Peter Russell写道:
> I think the way I use channel must be wrong, could any one tell me why?

Because the channel is unbuffered, the sending goroutine blocks until a goroutine receives a value from the channel. There is no other goroutine, so it's a deadlock.


I converted the unbuffered channel to a buffered channel and I think it works the way you expect.

Message has been deleted

feeling4t

unread,
Jul 24, 2012, 1:57:06 AM7/24/12
to golan...@googlegroups.com, feeling4t
This makes me clear, Thank U : )

在 2012年7月24日星期二UTC+8上午11时50分54秒,Daniel Bos写道:
Reply all
Reply to author
Forward
0 new messages