当一个goroutine在I/O操作上阻塞时,调度器是如何识别它已经停止阻塞的呢?

huangapple go评论85阅读模式
英文:

When a goroutine blocks on I/O how does the scheduler identify that it has stopped blocking?

问题

根据我所阅读的这里,Golang调度器会自动判断一个goroutine是否在进行I/O阻塞,并会自动切换到另一个没有被阻塞的线程来处理其他的goroutine。

我想知道的是调度器是如何确定那个goroutine已经停止了I/O阻塞的。

它是不是会定期进行一些轮询来检查是否仍然处于阻塞状态?是否有一个后台线程在运行,检查所有goroutine的状态?


举个例子,如果你在一个goroutine中执行一个需要5秒钟才能得到响应的HTTP GET请求,那么在等待响应的过程中它会被阻塞,而调度器会切换到处理另一个goroutine。那么,当服务器返回响应时,调度器是如何知道响应已经到达,并且是时候回到执行这个GET请求的goroutine来处理GET请求的结果呢?

英文:

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?

答案1

得分: 12

所有的输入/输出必须通过系统调用进行,而在Go语言中,系统调用的实现方式是通过由运行时控制的代码来调用的。这意味着当你调用一个系统调用时,运行时会被通知你想要进行的系统调用,然后代表goroutine执行它,而不是直接调用它(从而放弃对线程的控制权,将其交给内核)。这使得它能够执行非阻塞的系统调用,而不是阻塞的系统调用(基本上是告诉内核:“请执行这个操作,但不要阻塞直到完成,立即返回,并在结果准备好后通知我”)。这使得它能够同时进行其他工作。

英文:

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.

huangapple
  • 本文由 发表于 2016年4月8日 08:27:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/36489498.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定