duanfuchi7236 2014-08-28 02:30
浏览 37
已采纳

两个例程在同一通道上进行通信

I have a function that, given a slice and an array, will send the elements of the slice to the channel one by one

Link to playground

package main

import (
    "fmt"
)

var list1 = []string{"1", "2", "4"}

var list2 = []string{"11", "22", "44"}

func throw(ch chan string, list []string) {
    for _, el := range list {
        fmt.Println("Thrown ", el)
        ch <- el

    }
    close(ch)
    return
}

func main() {
    c := make(chan string)
    go throw(c, list1)
    go throw(c, list2)
    for i := range c {
        fmt.Println("received ", i)
    }
}

At some point the channel get closed, but one of the functions still needs to send data to it. How should I handle this? Making to separate channel seems the most reasonable choice here, but I want both data to pass through the same channel.

  • 写回答

1条回答 默认 最新

  • dongtuhe0506 2014-08-28 03:20
    关注

    Go expects the code on the sending side of the channel to know whether the channel has been closed or not. So code like your snippet where each goroutine can close the channel without regard for the other is buggy.

    One solution is to use a sync.WaitGroup to coordinate when each goroutine has completed, and have a third goroutine perform the close. So you'd modify your throw function to look something like:

    func throw(ch chan string, list []string, wg *sync.WaitGroup) {
        defer wg.Done()
        // current body of function, without the close() call
    }
    

    And change the code that spawns the goroutines to the following:

    var wg sync.WaitGroup
    wg.Add(2)
    go throw(c, list1, &wg)
    go throw(c, list2, &wg)
    go func() {
        wg.Wait()
        close(c)
    }()
    

    This way your channel will only be closed after the other two goroutines complete. You can experiment with this modified version of your example here: http://play.golang.org/p/nUiwjGglgU

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

报告相同问题?

悬赏问题

  • ¥50 .net core 并发调用接口问题
  • ¥15 网上各种方法试过了,pip还是无法使用
  • ¥15 用verilog实现tanh函数和softplus函数
  • ¥15 Hadoop集群部署启动Hadoop时碰到问题
  • ¥15 求京东批量付款能替代天诚
  • ¥15 slaris 系统断电后,重新开机后一直自动重启
  • ¥15 QTableWidget重绘程序崩溃
  • ¥15 如何解决智能小车直道抖动
  • ¥15 谁能帮我看看这拒稿理由啥意思啊阿啊
  • ¥15 关于vue2中methods使用call修改this指向的问题