Golang – 库是否需要是非阻塞的?

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

Golang - do libraries need to be non-blocking?

问题

我理解的是,非阻塞的网络服务器(如node.js、eventmachine、tornado)如果调用了一个阻塞库,可能会停止运行。对于Golang也是这样吗?如果一个goroutine被阻塞,另一个goroutine会自动获得CPU的访问权限,还是它们必须等待被阻塞的goroutine“让出”?如果是前者,那么库就不需要是非阻塞的,是吗?我之所以问是因为我没有看到任何明确说明它们是非阻塞的Redis/Mongo库。

英文:

My understanding is that non-blocking web servers (node.js, eventmachine, tornado) can grind to a halt if they make a call to a blocking library. Is this true for Golang as well? If one goroutine gets blocked, is another one automatically given access to the CPU, or do they have to wait for the blocked goroutine to 'yield'? If it is the former, then libraries don't need to be non-blocking, do they? I ask because I haven't seen any Redis/Mongo libraries that explicitly state that they're non-blocking.

答案1

得分: 8

Go routines不会因为调用阻塞库而停止运行,它们会在IO操作时让出CPU,或者运行时会根据需要创建新的操作系统线程。

如果一个go routine被阻塞,另一个go routine会自动获得CPU的访问权限。

它们不需要等待被阻塞的go routine“让出”。

因此,库(或者一般的Go代码)不需要是非阻塞的,这使得编写和维护它们更加容易。这是Go的一个重要优点。运行时会运行成千上万个go routines,而你只需要编写简单的命令式代码。

英文:

> My understanding is that non-blocking web servers (node.js,
> eventmachine, tornado) can grind to a halt if they make a call to a
> blocking library. Is this true for Golang as well?

No it isn't. Go routines will yield on IO or the runtime will create new OS threads as necessary.

> If one goroutine gets blocked, is another one automatically given
> access to the CPU

Yes it is - go routines yield on any sort of IO or channel communication.

> or do they have to wait for the blocked goroutine to 'yield'?

No they don't.

> If it is the former, then libraries don't need to be non-blocking, do
> they? I ask because I haven't seen any Redis/Mongo libraries that
> explicitly state that they're non-blocking.

No libraries (or Go code in general) don't need to be non blocking which makes them much easier to write and maintain. This is a major plus point of Go in my opinion. The runtime does the clever bit running 1000s of go routines and you just write simple imperative code.

huangapple
  • 本文由 发表于 2013年7月25日 07:24:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/17846505.html
匿名

发表评论

匿名网友

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

确定