代码如下:
func main() {
// Allocate 1 logical processors for the scheduler to use.
runtime.GOMAXPROCS(1)
// Add a count of two, one for each goroutine.
wg.Add(2)
// Create two goroutines.
fmt.Println("Create Goroutines")
go printPrime("B")
go printPrime("A")
// Wait for the goroutines to finish.
fmt.Println("Waiting To Finish")
wg.Wait()
fmt.Println("Terminating Program")
}
// printPrime displays prime numbers for the first 5000 numbers.
func printPrime(prefix string) {
// Schedule the call to Done to tell main we are done.
defer wg.Done()
next:
for outer := 2; outer < 5000; outer++ {
for inner := 2; inner < outer; inner++ {
if outer%inner == 0 {
continue next
}
}
fmt.Printf("%s:%d\n", prefix, outer)
}
fmt.Println("Completed", prefix)
}
运行结果如下:
//
Create Goroutines
Waiting To Finish
A:2
A:3
A:5
A:7
A:11
A:13
A:17
A:19
A:23
...
B:2
B:3
B:4999
Completed B
A:3767
A:3769
...
Completed A
Terminating Program
为什么会输出素数的时候先显示B:2 而不是先显示A:2?
go printPrime("B")
go printPrime("A")
这两条goruntine的执行顺序是什么样子的?