dtn55928 2016-05-10 15:12
浏览 13
已采纳

并发无法按我期望的那样工作

I am trying to understand why my code does not work, so I managed to recreate the problem in a simpler example.

I expected this code to output the string "broadcasted", but it does not output anything.

package main

import (
    "fmt"
    "time"
)

type hub struct {
    handle    chan []byte
    broadcast chan []byte
}

func (h *hub) init() {
    for {
        select {
        case m := <-h.handle:
            handler(m)
        case _ = <-h.broadcast:
            fmt.Println("broadcasted")
        }
    }
}

var socketHub = hub{
    handle:    make(chan []byte),
    broadcast: make(chan []byte),
}

func main() {

    go socketHub.init()

    m := []byte("this is the message")
    socketHub.handle <- m

    time.Sleep(time.Second * 2)
}

func handler(m []byte) {
    // Do some stuff.
    socketHub.broadcast <- m
}

Why does this not work?

  • 写回答

1条回答 默认 最新

  • dongwh1992 2016-05-10 15:23
    关注

    Your broadcast channel is unbuffered. This means that:

    1. You send the message to the handle channel: main goroutine blocks until...
    2. In the goroutine, the select case gets the message...
    3. And calls (in the goroutine) handler, which sends the message to the broadcast channel, blocking until...

    And that's it: your child goroutine is blocking, waiting on itself to pick the message. Concurrently, your main goroutine sleeps, then reaches the end of main, exits and terminates the program.

    You can 'solve' it in several ways:

    • Make your broadcast channel buffered: this way, goroutine sends the message, which succeeds immediately, and returns in the for loop, selecting it back and printing as intended
    • Make your send a (new) goroutine, either in handler, or by calling go handler(m) in your loop
    • Have two different goroutines listen to handler and broadcast

    Which one you choose depends on the exact problem you try to solve: in this tiny example, it's hard to find a 'best' one.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line