且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

当goroutine阻塞I / O时,调度程序如何识别它已经停止了阻塞?

更新时间:2023-11-14 15:32:40

所有I / O都必须通过系统调用完成,系统调用的方式在Go中实现,它们始终通过代码进行调用,运行时间。这意味着当你调用一个系统调用时,不是直接调用它(因此放弃了对内核线程的控制),运行时会收到你想要调用的系统调用的通知,并且它代表goroutine进行调用。例如,它允许它做一个非阻塞的系统调用,而不是阻塞的系统调用(实质上告诉内核,请做这件事,但不要阻塞,直到完成,立即返回,并且一旦结果让我知道准备好了)。这允许它在此期间继续进行其他工作。

From what I've read here, the golang scheduler will automatically determine if a goroutine is blocking on I/O, and will automatically switch to processing others goroutines on a thread that isn't blocked.

What I'm wondering is how the scheduler then figures out that that goroutine has stopped blocking on I/O.

Does it just do some kind of polling every so often to check if it's still blocking? Is there some kind of background thread running that checks the status of all goroutines?


For example, if you were to do an HTTP GET request inside a goroutine that took 5s to get a response, it would block while waiting for the response, and the scheduler would switch to processing another goroutine. Now given that, when the server returns a response, how does the scheduler understand that the response has arrived, and it's time to go back to the goroutine that made the GET so that it can process the result of the GET?

All I/O must be done through syscalls, and the way syscalls are implemented in Go, they are always called through code that is controlled by the runtime. This means that when you call a syscall, instead of just calling it directly (thus giving up control of the thread to the kernel), the runtime is notified of the syscall you want to make, and it does it on the goroutine's behalf. This allows it to, for example, do a non-blocking syscall instead of a blocking one (essentially telling the kernel, "please do this thing, but instead of blocking until it's done, return immediately, and let me know later once the result is ready"). This allows it to continue doing other work in the meantime.