当goroutine阻塞I / O时,调度程序如何识别它已经停止了阻塞? [英] When a goroutine blocks on I/O how does the scheduler identify that it has stopped blocking?

查看:183
本文介绍了当goroutine阻塞I / O时,调度程序如何识别它已经停止了阻塞?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从我读过的这里,golang调度程序将自动确定一个goroutine是否阻止I / O,并且会自动切换到在未被阻塞的线程上处理其他goroutines。



我想知道的是调度程序如何计算出goroutine已经停止了对I / O的阻塞。

它是否每隔一段时间都进行一次轮询以检查它是否仍然阻塞?是否有某种背景线程运行,检查所有goroutines的状态?






例如,如果您要做一个goroutine中的GET请求需要5s才能得到响应,它会在等待响应时阻塞,并且调度器将切换到处理另一个goroutine。现在,当服务器返回响应时,调度程序如何理解响应已经到达,是时候回到构建GET的goroutine,以便它可以处理GET的结果?

解决方案

所有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.

这篇关于当goroutine阻塞I / O时,调度程序如何识别它已经停止了阻塞?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆