Please help me to understand goroutines starting order

package main

import "fmt"

func sum(a []int, c chan int) {
fmt.Println("ARRAY", a)
sum := 0
for _, v := range a {
	sum += v
 c <- sum // send sum to c

 func main() {
a := []int{7, 2, 8, -9, 4, 0}

c := make(chan int)

go sum(a[len(a)/2:], c) //first
go sum(a[0:len(a)/2], c) // second
x, y := <-c, <-c // receive from c

fmt.Println(x, y, x+y)

in this example we launch 2 goroutines, first one (go sum(a[len(a)/2:], c) is a slice of int array with values ( -9, 4, 0) and the second one is also a slice of int (7, 2, 8) , my question is why we recieve 17 faster then -5 although we launch -5’s goroutine first, and can you give me a references where i can read about councurency, channels

There is no defined order - they run concurrently. Which one happens to start first and/or finish first is random.

Perhaps it helps if you don’t think of the “go” keyword as “launching” a goroutine - see it as creating a goroutine data structure and putting it in the pool of runnable goroutines. The runtime scheduler will look in this pool at some point and start executing the routines, potentially creating new threads to run them if necessary, etc.

It’s also not deterministic which of two channel senders will complete first. Let’s assume that your goroutines started up instantly and completed instantly. When you reach the first <-c in your code (in the ... := <-c, <-c) there will be two routines trying to send to the channel. Which one gets picked to do the first write is random and ends up in x. The other one will get to serve the second read and ends up in y.

so if i will run my code many times the output may change from 17 -5 12 to -5 17 12 ?


let me repeat the goroutines has no order to run it, just put it on the stack and runtime at some point decides which gorountine will be launched, even if there is 100 goroutines, perhaps the 77th gorountine will execute first, and when we will want to perform data from the channel, if 100 gorountines are ready to send data, runtime will randomly select one gorountine and other goroutines have to wait to the next oportunity to send data, am i right ?


thank you very much

try limiting
runtime.GOMAXPROCS(1) => 2
and try to understand what is happening. There is no defined order though :stuck_out_tongue:

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.