douye9175 2016-09-19 14:51
浏览 8

使用golang频道。 获得“所有goroutine都在睡觉-死锁!”

iam currently playing around with go routines, channels and sync.WaitGroup. I know waitgroup is used to wait for all go routines to complete based on weather wg.Done() has been called enough times to derement the value set in wg.Add(). i wrote a small bit of code to try to test this in golang playground. show below

var channel chan int
var wg sync.WaitGroup

func main() {

  channel := make(chan int)
  mynums := []int{1,2,3,4,5,6,7,8,9} 

  go addStuff(mynums)

 func addStuff(mynums []int) {

   for _, val := range mynums {
       channel <- val

 func recieveStuff(channel chan int) {
    for val := range channel{

Iam getting a deadlock error. iam trying to wait on the routing to return with wg.Wait()? then, close the channel. Afterwards, send the channel to the recievestuff method to output the values in the slice? but it doesnt work. Ive tried moving the close() method inside the go routine after the loop also as i thought i may of been trying to close on the wrong routine in main(). ive found this stuff relatively confusing so far coming from java and c#. Any help is appreciated.

  • 写回答

1条回答 默认 最新

  • douhulao7642 2016-09-19 15:01

    The call to wg.Wait() wouldn't return until wg.Done() has been called once.

    In addStuff(), you're writing values to a channel when there's no other goroutine to drain those values. Since the channel is unbuffered, the first call to channel <- val would block forever, resulting in a deadlock.

    Moreover, the channel in addStuff() remains nil since you're creating a new variable binding inside main, instead of assigning to the package-level variable. Writing to a nil channel blocks forever:

    channel := make(chan int) //doesn't affect the package-level variable

    Here's a modified example that runs to completion by consuming all values from the channel:

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



  • ¥15 Mac虚拟机安装Windows,Windows中用idea跑项目,报错process finished with exit code -1073741819(0xc0000005) 如何解决?
  • ¥15 关于python爬虫返回js数据结构的处理
  • ¥15 ubuntu所用stm32标准库开发烧录没反映
  • ¥15 运维工程师(在职人员回答)
  • ¥15 Kmeans的趋势分析有会的吗
  • ¥20 R语言单细胞测序 对seurat对象进行标准化时出现问题
  • ¥15 请问如何在matlab里使用raven工具?
  • ¥100 关于ios手游充值到一定金额,再点充值提示公众号的问题。
  • ¥15 求一个stm32串口控制程序
  • ¥20 Windows 驱动开发版本疑问相关