I’m keeping myself learning Go and I’m at Chapter “concurrency and channels”.
I have one array that contains 4 []int
For each this 4 []int I do some operations and pass the result to a channel.
Then I merge the result to an array that contains the result of the 4 go routines.
the code:
result := []int{}
ch := make(chan []int)
[...] // load slices
for i := 0; i < numberArray; i++ {
go func(sli []int, i int, ch chan<- []int) {
sort.Sort(sort.IntSlice(sli))
fmt.Println("sorted subarray #", i, sli)
ch <- sli
}(slices[i], i, ch)
}
for i := 0; i < numberArray; i++ {
result = append(result, <-ch...)
}
Question:
If the go routines are executed concurrently how it’s possible that at the end I am able to merge the result of each go routine to an array “result”. I have difficulties to understand how the data are transmitted to the channel. Is the last block executed when all go routine are finished ?
Why I don’t need to have a channel created with make(chan []int, 4) ? I thought I need a channel that contains exactly the same length of go-routine so that all the results are well received.
(1) for i := 0; i < numberArray; i++ {
(2) go func(sli []int, i int, ch chan<- []int) {
(3) sort.Sort(sort.IntSlice(sli))
(4) fmt.Println("sorted subarray #", i, sli)
(5) ch <- sli
(6) }(slices[i], i, ch)
(7)}
(8)for i := 0; i < numberArray; i++ {
(9) result = append(result, <-ch...)
(10)}
When you reach the line (9), the channel reading blocks current thread execution and triggers the execution of gorutines
the goroutine is executed and then reach line (5), the control
is returned to main thread (Line 9) and reads the value from the channel
adding to slide
Go to next iteration (8), reach line (9) and the process starts over
Thank you for your answer.
is the first go routine executed when it comes first to line 9 and after it executed line 9?
Sorry this is a bit difficult to me
When executes <- ch, the current thread is blocked, allowing gorutines to be executed and then in the goroutine, ch <- sli blocks the goroutine and turns execution to main thread, when the <- ch is complete and the value in the channel is read.
In Line(2) just defines the goroutine, which it is invoke as the main thread get blocked.
Here a good tutorial https://golangbot.com/goroutines/ (and other constructs in golang)
yes, the first time is somekind difficult to grasp on…
Thanks a lot for the link, it help me a lot to understand how it works:
Thanks:
When a new Goroutine is started, the goroutine call returns immediately. Unlike functions, the control does not wait for the Goroutine to finish executing. The control returns immediately to the next line of code after the Goroutine call and any return values from the Goroutine are ignored.