Does the goroutines created in the same goroutines execute always in order?

Issue

package main

func main() {
        c:=make(chan int)
        for i:=0; i<=100;i++ {
                i:=i
                go func() {
                        c<-i
                }() 
        }   
        for {
                b:=<-c
                println(b)
                if b==100 {
                        break
                }   
        }   
}

The above code created 100 goroutines to insert num to channel c, so I just wonder that, will these goroutines execute in random orders? During my test, the output will always be 1 to 100

Solution

What you observe as “random” behaviour is, more strictly, non-deterministic behaviour.

To understand what is happening here, think about the behaviour of the channel. In this case, it has many goroutines trying to write into the channel, and just one goroutine reading out of the channel.

The reading process is simply sequential and we can disregard it.

There are many concurrent writing processes and they are competing to access a shared resource (the channel). The channel has to make choices about which message it will accept.

When a Communicating Sequential Process (CSP) network makes a choice, it introduces non-determinism. In Go, there are two ways that this kind of choice happens:

  • concurrent access to one of the ends of a channel, and
  • select statements.

Your case is the first of these.

CSP is an algebra that allows concurrent behaviours to be analysed and understood. A seminal publication on this is Roscoe and Hoare “The Laws of Occam Programminghttps://www.cs.ox.ac.uk/files/3376/PRG53.pdf (similar ideas apply to Go also, although there are small differences).

Surprisingly, the concurrent execution of goroutines is fully deterministic. It’s only when choices are made that non-determinism comes in.

Answered By – Rick-777

Answer Checked By – Clifford M. (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.