两个逻辑处理器处理两个goruntine并发运行时如何确定哪个goruntine先运行?

zhangyang9 · 2017-12-17 03:56:08 · 1063 次点击 · 大约8小时之前 开始浏览    置顶
这是一个创建于 2017-12-17 03:56:08 的主题,其中的信息可能已经有所发展或是发生改变。

代码如下:

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的执行顺序是什么样子的?


有疑问加站长微信联系(非本文作者)

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

1063 次点击  
加入收藏 微博
1 回复  |  直到 2017-12-17 04:28:02
mortemnh
mortemnh · #1 · 7年之前

print是IO操作,Goroutine会在IO操作的时候必然发生一次调度,结果就是通过print去看是否程序逻辑执行是不可靠的。

添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传