Go goroutine是一个协程? [英] Is a Go goroutine a coroutine?

查看:138
本文介绍了Go goroutine是一个协程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Google I / O 2012演示文稿中, Go Concurrency Patterns Rob> Pike提到几个 goroutines 可以存在于一个线程中。这是否意味着它们被实现为协程?如果不是,他们如何实施?链接到源代码将是受欢迎的。

In the Google I/O 2012 presentation Go Concurrency Patterns, Rob Pike mentions that several goroutines can live in one thread. Does this imply that they are implemented as coroutines? If not, how they are implemented? Links to source code would be welcome.

推荐答案

不完全。 Go FAQ部分 为什么使用goroutines而不是线程? 解释:

Not quite. The Go FAQ section Why goroutines instead of threads? explains:


Goroutines是使并发易于使用的一部分。这个想法已经存在了一段时间,它将独立执行的函数 - 协程 - 复用到一组线程中。当协程阻塞时,例如通过调用阻塞系统调用,运行时会自动将同一操作系统线程上的其他协同程序移动到不同的可运行线程,这样它们就不会被阻塞。程序员没有看到这一点,这是关键。我们称之为goroutines的结果可能非常便宜:除非他们花费大量时间在长时间运行的系统调用中,否则它们的成本只比堆栈的内存要少,仅为几千字节。

Goroutines are part of making concurrency easy to use. The idea, which has been around for a while, is to multiplex independently executing functions—coroutines—onto a set of threads. When a coroutine blocks, such as by calling a blocking system call, the run-time automatically moves other coroutines on the same operating system thread to a different, runnable thread so they won't be blocked. The programmer sees none of this, which is the point. The result, which we call goroutines, can be very cheap: unless they spend a lot of time in long-running system calls, they cost little more than the memory for the stack, which is just a few kilobytes.

为了使堆栈变小,Go的运行时使用分段堆栈。新铸造的goroutine有几千字节,几乎总是足够的。如果不是,则运行时自动分配(并释放)扩展段。每个函数调用的开销平均值约为三个廉价指令。在相同的地址空间中创建数十万个goroutines是实用的。如果goroutines只是线程,那么系统资源将会用得更少。

To make the stacks small, Go's run-time uses segmented stacks. A newly minted goroutine is given a few kilobytes, which is almost always enough. When it isn't, the run-time allocates (and frees) extension segments automatically. The overhead averages about three cheap instructions per function call. It is practical to create hundreds of thousands of goroutines in the same address space. If goroutines were just threads, system resources would run out at a much smaller number.

这篇关于Go goroutine是一个协程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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