doubiaozhan0745 2013-09-10 02:51
浏览 140
已采纳

Golang-在结构内部使用chan slice

I am trying to use a slice chan type inside a struct, similar to the code below. However, when I try to receive at

test := <-c.slice

The program hangs. Is there a way to do this?

package main

import "fmt"

type blah struct {
    slice chan [][]int
}

func main() {

    slice := make([][]int, 3)
    c := blah{make(chan [][]int)}

    slice[0] = []int{1, 2, 3}
    slice[1] = []int{4, 5, 6}
    slice[2] = []int{7, 8, 9}

    go func() {
        test := <- c.slice
        test = slice
        c.slice <- test
    }()

    fmt.Println(<-c.slice)
}
  • 写回答

1条回答 默认 最新

  • douling6469 2013-09-10 03:23
    关注

    The first line inside the goroutine receives from the channel, and so does the first line in main after the goroutine is created. That means the only two goroutines in the system are both trying to receive from the slice channel, and nobody is trying to send into it.

    More generally, the issue is that for somebody to receive (consume), somebody else has to concurrently send (produce). If the channel was buffered, which isn't the case in your example, the send might also happen ahead of time in the same goroutine.

    So this works, for example, because the channel has a buffer of one element, which means the send won't block:

    ch := make(chan int, 1)
    ch <- 1
    i := <-ch
    

    This works as well, because the send is happening concurrently with the receive:

    ch := make(chan int)
    go func() { ch <- 1 }()
    i := <-ch
    

    This does not work, because both goroutines are trying to send into an unbuffered channel, and nobody is trying to receive:

    ch := make(chan int)
    go func() { ch <- 1 }()
    ch <- 2
    

    This does not work either, because both goroutines are trying to receive, and nobody is trying to send:

    ch := make(chan int)
    go func() { <-ch }()
    <-ch
    

    That last one is your case.

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

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里