gpt4 book ai didi

go - 广播公司 : all goroutines are asleep - deadlock

转载 作者:IT王子 更新时间:2023-10-29 00:52:44 24 4
gpt4 key购买 nike

下面的代码 ( 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

最佳答案

这是在 for-range 循环中重新分配 c 引起的一个微妙错误。看起来有点奇怪,但是您在 std 库中的几个地方看到了这种模式:

func (b *Broadcaster) Broadcast(msg string) {
for _, c := range b.Clients {
c := c // redeclare c for the closure
go func() {
c.Inbox() <- msg
}()
}
}

http://golang.org/doc/faq#closures_and_goroutines

关于go - 广播公司 : all goroutines are asleep - deadlock,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23922682/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com