Returning Golang Canals

I am trying to use Go feeds and are confused with the below example function from the go blog:

func gen(nums []int) <-chan int { out := make(chan int) go func() { for _, n := range nums { out <- n } close(out) }() fmt.Println("return statement is called ") return out } 

Home:

 func main() { c := make(<-chan int) c = gen([]int{2, 3, 4, 5}) // Consume the output.//Print 2,3,4,5 fmt.Println(<-c) fmt.Println(<-c) fmt.Println(<-c) fmt.Println(<-c) } 

Completion Code: http://play.golang.org/p/Qh30wzo4m0

My doubts: 1.My understanding was, as soon as the return is called a function, it will be stopped, and the channel inside this function will no longer have life.Here the return statement is called only once. But the contents of the Out channel are received many times. In this case, how is the actual thread of execution? I am new to parallel programming. Don't forget to help

+5
source share
2 answers
 out := make(chan int) 

This is not a buffered channel, which means that out <- n will block until someone reads that channel somewhere (calls fmt.Println(<-c) )
(See also " keeping the golang channel in order )"

Thus, returning at the end of the gen() function does not mean that the go func() literal terminates (since it is still waiting for readers to consume the content of the out channel).

But the main function receives the out channel as a return from the gen() function.
How can it be obtained after the completion of gen() ?

The fact that the completion of gen() does not affect its return value ( out channel): the purpose of " gen() " is to "generate" this out channel.

main can use out (as the return value of gen() ) after gen() .

The literal go func inside gen() is still executing, even if gen() completes.

+5
source

Because gen() disables the channel population function like goroutine;

 go func() { for _, n := range nums { out <- n } close(out) }() 

and it blocks when the first value is sent on the out channel because nothing has been received yet (block of unbuffered channels when sent until something is received on them), this goroutine does not end when the gen() function returns .

Gets from c in main()

 fmt.Println(<-c) ... 

then run goroutine running in gen() to continue filling the channel as the results are read, and then finally main() returns when goroutine returns, because there is nothing to send to out , and nothing left to receive on c .

In addition, c := make(<-chan int) in main() not required, since gen() creates a channel and returns it.

See Playground

+1
source

Source: https://habr.com/ru/post/1213684/


All Articles