【发布时间】:2014-05-29 17:06:30
【问题描述】:
下面的代码 (http://play.golang.org/p/ikUtdoKOo5) 应该向多个客户端广播一条消息。但它不起作用,我不知道为什么。
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'\n", <-client1.Messages)
fmt.Printf("client2: '%s'\n", <-client2.Messages)
}
错误:
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
更新:
go vet 工具揭示了问题:
% go vet
main.go:12: range variable c enclosed by function
【问题讨论】:
标签: go