本文介绍了在相同的例程中创建的例程是否总是按顺序执行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
package main
func main(){
c:= make(chan int)
for i:= 0; i i:= i
go {{b} {
c< -i
}()
}
for { b $ bb:=< -c
println(b)
if b == 100 {
break
}
}
}
上面的代码创建了100个goroutines来将num插入到通道c,所以我只是想知道,这些goroutines会在随机订单?在我的测试过程中,输出将始终为1到100
解决方案非确定性行为。
要理解这里发生的事情,请考虑频道的行为。在这种情况下,它有很多goroutines试图写入频道,并且只有一个goroutine读出频道。
阅读过程只是顺序的,我们可以忽略它。
有许多并发写入过程,它们正在竞争访问共享资源(通道)。当通信顺序过程(CSP)网络进行 选择时,通道必须做出关于哪个消息可以接受的选择。 ,它引入了 非确定性 。在Go中,有两种方式可以进行这种选择:
是第一个。
CSP是一个代数,允许分析和理解并发行为。关于此的一本开创性的出版物是Roscoe和Hoare(类似的想法也适用于Go,尽管差别不大)。
令人惊讶的是,goroutines的并发执行是完全确定性的。只有在做出选择时非决定论才会出现。
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
解决方案
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.
这篇关于在相同的例程中创建的例程是否总是按顺序执行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!