当goroutine被IO绑定操作阻塞时,它们(以及运行它们的OS线程)的行为如何? [英] How do goroutines (and the OS threads running them) behave when they get blocked by an IO bound operation?

查看:72
本文介绍了当goroutine被IO绑定操作阻塞时,它们(以及运行它们的OS线程)的行为如何?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们假设一个goroutine正在从网络中读取.每次goroutine必须等待(被阻塞以等待网络响应)时,会发生什么?运行goroutine的OS线程是否被阻塞?还是像C#中的异步操作一样工作(线程返回线程池,直到操作系统的IO线程通知程序有新数据要处理,然后线程池中的另一个线程继续处理数据)从网络上收到)?

Let's suppose that a goroutine is reading from the network. Every time the goroutine has to wait (gets blocked waiting for the network to respond), what happens? Does the OS thread running the goroutine get blocked? Or does it work like an async operation in C# (where the thread returns to the thread pool until the IO thread of the operative system notifies the program that there's new data to process, and then, another thread from the thread pool continues processing the data received from the network)?

我主要担心的是,如果Go在每次goroutine被阻塞时都保持一个阻塞的线程,如果我的服务器中有许多goroutine在处理来自非常慢的网络的传入连接,那么我可能最终会耗尽RAM,因为每一个这些阻塞的线程中的大约消耗了2MB的RAM.或者,如果由Go创建的用于运行goroutine的线程池有限制,那么我可能最终会失去活力.

My main worry is that if Go keeps a blocked thread every time a goroutine gets blocked, if I have many goroutines in a server processing incoming connections from a very slow network, I may end up running out of RAM, since each one of those blocked threads consumes about 2MB of RAM. Or if the thread pool created by Go to run goroutines has a limit, I may end up running out of liveliness.

那么goroutine在IO绑定操作中如何表现?

So how do goroutines behave in IO bound operations?

推荐答案

如果它是异步syscall,它将阻塞goroutine并释放线程以运行另一个goroutine,就像goroutine在例如阻塞.频道阅读.

If it's an async syscall, it blocks the goroutine and frees the thread to run another goroutine, same as if the goroutine is blocking on e.g. a channel read.

如果这是阻塞的系统调用,那么Go对此无能为力-系统调用将阻塞线程,句点.Go可能会启动另一个线程来处理调度程序确定的可运行goroutine.

If it's a blocking syscall, there's nothing Go can do about that - the syscall will block the thread, period. Go may spin up another thread to handle runnable goroutines as determined by the scheduler.

这篇关于当goroutine被IO绑定操作阻塞时,它们(以及运行它们的OS线程)的行为如何?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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