douyuan1049 2014-05-28 22:06
浏览 42
已采纳

广播员:所有goroutine都在睡眠中-死锁

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
  • 写回答

2条回答 默认 最新

  • dr2898 2014-05-28 22:39
    关注

    This is a subtle bug brought on by the reassignment of c in the for-range loop. It looks a little strange, but you see this pattern in the std library in a few places:

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵