Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Golang blocking and non blocking

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?

like image 878
Roger Johansson Avatar asked Mar 20 '16 10:03

Roger Johansson


1 Answers

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

like image 107
Not_a_Golfer Avatar answered Oct 03 '22 21:10

Not_a_Golfer