goroutine 是如何工作的?(或:goroutines 和 OS 线程的关系) [英] How do goroutines work? (or: goroutines and OS threads relation)

查看:16
本文介绍了goroutine 是如何工作的?(或:goroutines 和 OS 线程的关系)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

其他 goroutine 如何在调用系统调用的同时继续执行?(当使用 GOMAXPROCS=1 时)
据我所知,在调用系统调用时,线程放弃控制,直到系统调用返回.Go 如何在不为每个系统调用阻塞 goroutine 创建系统线程的情况下实现这种并发性?

How can other goroutines keep executing whilst invoking a syscall? (when using GOMAXPROCS=1)
As far as I'm aware of, when invoking a syscall the thread gives up control until the syscall returns. How can Go achieve this concurrency without creating a system thread per blocking-on-syscall goroutine?

来自文档:

协程

它们被称为 goroutines 因为现有的术语——线程,协程、进程等——传达了不准确的内涵.一个goroutine 有一个简单的模型:它是一个并发执行的函数与同一地址空间中的其他 goroutine.它重量轻,成本只比堆栈空间的分配多一点.和堆栈从小处开始,所以它们很便宜,并通过分配(和释放)来增长根据需要堆存储.

They're called goroutines because the existing terms—threads, coroutines, processes, and so on—convey inaccurate connotations. A goroutine has a simple model: it is a function executing concurrently with other goroutines in the same address space. It is lightweight, costing little more than the allocation of stack space. And the stacks start small, so they are cheap, and grow by allocating (and freeing) heap storage as required.

Goroutines 被多路复用到多个 OS 线程上,所以如果一个人应该阻塞,例如在等待 I/O 时,其他人继续运行.他们的设计隐藏了线程创建的许多复杂性和管理.

Goroutines are multiplexed onto multiple OS threads so if one should block, such as while waiting for I/O, others continue to run. Their design hides many of the complexities of thread creation and management.

推荐答案

如果一个 goroutine 被阻塞,runtime 将启动一个新的 OS 线程来处理其他 goroutine,直到阻塞的那个 goroutine 停止阻塞.

If a goroutine is blocking, the runtime will start a new OS thread to handle the other goroutines until the blocking one stops blocking.

参考:https://groups.google.com/forum/#!topic/golang-nuts/2IdA34yR8gQ

这篇关于goroutine 是如何工作的?(或:goroutines 和 OS 线程的关系)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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