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

隐身守侯 提交于 2019-11-29 15:35:24

问题


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


回答1:


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 Programming" https://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.




回答2:


No, they are not guaranteed to run in order. With GOMAXPROCS=1 (the default) they appear to, but this is not guaranteed by the language spec.

And when I run your program with GOMAXPROCS=6, the output is non-deterministic:

$ GOMAXPROCS=6 ./test
2
0
1
4
3
5
6
7
8
9
...

On another run, the output was slightly different.

If you want a set of sends on a channel to happen in order, the best solution would be to perform them from the same goroutine.



来源:https://stackoverflow.com/questions/29057210/does-the-goroutines-created-in-the-same-goroutines-execute-always-in-order

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!