【发布时间】:2016-03-15 12:36:43
【问题描述】:
根据我对 Go 调度器的理解,Go 调度算法是partially preemptive:goroutine 切换发生在 goroutine 调用函数或阻塞 I/O 时。
向频道发送消息时是否会发生 goroutine 切换?
// goroutine A
ch <- message
// some additional code without function calls
// goroutine B
message := <- ch
在上面的代码中,我想让A中ch <- message之后的代码在切换到B之前执行,这样可以保证吗?还是在 A 在ch 上发送消息后立即安排 B?
【问题讨论】:
-
依赖运行时的实现细节充满了危险。我会重新考虑你的代码。
-
很多时候没有运行时抢占。 Goroutines A 和 B 可能运行在由内核抢占的不同操作系统线程中,或者完全不同的 CPU 内核中。
标签: go scheduling channel goroutine