The code below (http://play.golang.org/p/ikUtdoKOo5) is supposed to broadcast a message to a number of clients. But it does not work and I can't figure out why.
package main
import "fmt"
type Broadcaster struct {
Clients []Client
}
func (b *Broadcaster) Broadcast(msg string) {
for _, c := range b.Clients {
go func() {
c.Inbox() <- msg
}()
}
}
type Client interface {
Inbox() chan string
}
type TestClient struct {
Messages chan string
}
func (tc TestClient) Inbox() chan string {
return tc.Messages
}
func main() {
client1 := TestClient{Messages: make(chan string)}
client2 := TestClient{Messages: make(chan string)}
broadcaster := Broadcaster{Clients: []Client{client1, client2}}
broadcaster.Broadcast("sos")
fmt.Printf("client1: '%s'
", <-client1.Messages)
fmt.Printf("client2: '%s'
", <-client2.Messages)
}
Error:
go run main.go
fatal error: all goroutines are asleep - deadlock!
goroutine 1 [chan receive]:
main.main()
/Users/artem/projects/gocode/src/github.com/artemave/broadcaster/main.go:36 +0x1f3
goroutine 3 [chan send]:
main.func·001()
/Users/artem/projects/gocode/src/github.com/artemave/broadcaster/main.go:12 +0x5f
created by main.(*Broadcaster).Broadcast
/Users/artem/projects/gocode/src/github.com/artemave/broadcaster/main.go:13 +0xcd
goroutine 4 [chan send]:
main.func·001()
/Users/artem/projects/gocode/src/github.com/artemave/broadcaster/main.go:12 +0x5f
created by main.(*Broadcaster).Broadcast
/Users/artem/projects/gocode/src/github.com/artemave/broadcaster/main.go:13 +0xcd
UPDATE:
The go vet tool reveals the problem:
% go vet
main.go:12: range variable c enclosed by function