Golang阻止和非阻塞 [英] Golang blocking and non blocking
问题描述
我对Go如何处理非阻塞IO有些困惑。
API大多与我同步,在Go上观看演示文稿时,听到像and the call blocks这样的评论并不少见
是使用阻止IO从文件或网络读取时?
或者有什么样的魔法在Go Routine中使用时重写代码?
从C#背景来看,这种感觉非常不合适直观,在C#中,当使用异步API时,我们有 await
关键字。
这明确表示API可以产生当前线程,并在延续时间内继续。
所以TLDR;
Go Go会在Go例程中执行IO时阻止当前线程,还是会将它转换为类似于异步状态的C#使用延续?
调度程序将在需要时分配系统线程,以及在真正阻塞的操作中我认为文件IO阻塞例如,或者调用C代码)。但是如果你正在做一些简单的http服务器,你可以拥有成千上万的goroutine,实际上使用了一些真正的线程。
您可以在这里阅读更多关于Go的内部工作原理: $ b https://morsmachine.dk/go-scheduler
I am somewhat confused over how Go handles non blocking IO. API's mostly look synchronous to me, and when watching presentations on Go, its not uncommon to hear comments like "and the call blocks"
Is Go using blocking IO when reading from files or network? Or is there some kind of magic that re-writes the code when used from inside a Go Routine?
Coming from a C# background, this feels very non intuitive, in C# we have the await
keyword when consuming async API's.
Which clearly communicates that the API can yield the current thread and continue later inside a continuation.
So TLDR; Will Go block the current thread when doing IO inside a Go routine, or will it be transformed into a C# like async await state machine using continuations?
Go has a scheduler that lets you write synchronous code, and does context switching on its own and uses async IO under the hood. So if you're running several goroutines, they might run on a single system thread, and when your code is blocking from the goroutine's view, it's not really blocking. It's not magic, but yes, it masks all this stuff from you.
The scheduler will allocate system threads when they're needed, and during operations that are really blocking (I think file IO is blocking for example, or calling C code). But if you're doing some simple http server, you can have thousands and thousands of goroutine using actually a handful of "real threads".
You can read more about the inner workings of Go here:
https://morsmachine.dk/go-scheduler
这篇关于Golang阻止和非阻塞的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!