代码如下:
![76540481-8DEB-46C9-B1C1-1FA08EB66C92.png](https://static.studygolang.com/171218/29f84a242b5e74fe36bbed76f71f3f20.png)
显示结果如下:
Create Goroutines
Waiting To Finish
D:2
D:3
D:5
D:7
...
D:43
D:47
Completed D
A:2
A:3
A:5
...
A:43
A:47
Completed A
B:2
B:3
...
B:43
B:47
Completed B
C:2
C:3
...
C:43
C:47
Completed C
Terminating Program
多次运行之后的显示的goroutine执行顺序都是:D>A>B>C ,为什么是这样的运行顺序?而不是 ABCD或者DACB等等呢?
可否有大神给讲解一下go逻辑处理器的运行原理以及执行多个goroutine时采用何种调度模型(队列?或者是其他?)?
```go
package main
import (
"fmt"
"runtime"
"sync"
)
var wg sync.WaitGroup
func main() {
runtime.GOMAXPROCS(1)
wg.Add(4)
fmt.Println("Create Goroutines")
go printPrime("A")
go printPrime("B")
go printPrime("C")
go printPrime("D")
fmt.Println("Waiting To Finish")
wg.Wait()
fmt.Println("Terminating Program")
}
func printPrime(prefix string) {
defer wg.Done()
next:
for outer := 2; outer < 50; outer++ {
for inner := 2; inner < outer; inner++ {
if outer%inner == 0 {
continue next
}
}
fmt.Printf("%s:%d\n", prefix, outer)
}
fmt.Println("Completed", prefix)
}
```
#3
更多评论
```go
package main
import (
"fmt"
"runtime"
"sync"
)
var wg sync.WaitGroup
func main() {
runtime.GOMAXPROCS(1)
wg.Add(4)
fmt.Println("Create Goroutines")
go printPrime("A")
go printPrime("B")
go printPrime("C")
go printPrime("D")
fmt.Println("Waiting To Finish")
wg.Wait()
fmt.Println("Terminating Program")
}
func printPrime(prefix string) {
defer wg.Done()
next:
for outer := 2; outer < 50; outer++ {
for inner := 2; inner < outer; inner++ {
if outer%inner == 0 {
continue next
}
}
fmt.Printf("%s:%d\n", prefix, outer)
}
fmt.Println("Completed", prefix)
}
```
#2