I followed the Go Tour and I get a little stuck when it comes to goroutines. I understand that they are very light and that every time a goroutine locks, another one starts, but I can’t understand how this example really works:
package main import ( "fmt" "time" ) func say(s string) { for i := 0; i < 5; i++ { time.Sleep(1000 * time.Millisecond) fmt.Println(s) } } func main() { go say("world") say("hello") }
Playground
I understand that goroutine is run for the say function with the argument "peace", but as I understand it, it should print "peace" five times and "hello" once. However, I do not understand why the conclusion is as it is:
hello world hello world hello world hello world hello
From my limited understanding of flows from other languages, the output should be something like this:
hello world world world world world
or like this:
world world world hello world world
Why is the second line also executed five times? Is anything below the go statement classified as part of the go procedure?
Also the following slide shows that I cannot lower my head again:
package main import "fmt" func sum(a []int, c chan int) { sum := 0 for _, v := range a { sum += v } c <- sum
Playground
Gorotin starts in the second half of the slice, and then the other for the first part of the slice, however, two different values are assigned to the x and y values. As I see it, the sum function will send this sum to channel c , and then the next sum will send the sum to the same channel c , and how can two different values be assigned to two variables? Should channel c have the same sum value?
I understand that this is a rather long question, but I could not find the answer to these questions.