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 Fiddler无法对部分小程序抓包
  • ¥60 Python代码 ip首部检验和计算代码 版本协议 首部长度 源地址 目的地址 存活时间
  • ¥18 微机原理汇编的综合实验
  • ¥15 LD衰减图用R语言对其可视化
  • ¥15 Mermaid语法生成的svg在Axure无法编辑
  • ¥15 Windchill二次开发
  • ¥15 怎么把tkinter和其他代码结合起来使功能可以完善
  • ¥15 爬取豆瓣电影相关处理
  • ¥15 手机淘宝抓清除消息接口
  • ¥15 C#无selenium