在子例程中进入频道

What is the best practice for creating channels in go programming? For organization and clarity, should you create all the channels in the main routine?

I have reviewed go code where channels are created inside child routine. Are these channels off-limits to the main routine when it is created in the child routine?

Please clarify. Thanks in advance.

Any goroutine can interact with any channel in its scope, just like any other variable. It doesn't really matter where the channel was created. What does matter, however, is that the goroutines communicating through the thread both have a reference to the channel.

The reason that the "forking" or "parent" goroutine typically creates the channel is that if the child created the channel, it wouldn't have any way to share it with the parent. Consider:

go func(){
  ch := make(chan int)
}
// how would we refer to `ch` out here?

It doesn't matter who creates the channel, there's no concept of channel "ownership" . But the goroutines writing to the channel do need to refer to it, which is why it's created in the "parent" thread and passed or shared with the goroutine. Otherwise, the parent would have no way to get the channel from the child (you could pass the channel in a channel but that kind of proves the point!)

I learned a lot about concurrency model in Go recommend articles. And i learn where to create a channel in different situations at the same time.

Such as, in Pipeline model, creating a channel at upstream stage, and passed it to a anonymous go routine. When the upstream stage finished, it can close the channel.

I hope these articles are helpful.