In Go, does it make sense to write non-blocking code?


Question

coming from node.js point of view, where all code is non-blocking.

In Go, non-blocking is easily achieved using channels.

if one were writing a node.js type server in go, does it make sense to make it non-blocking? for example, having a database connect() function return a channel, as versus blocking while waiting for the connection to occur.

to me, this seems the correct approach

but ...

1
38
10/5/2017 7:06:51 PM

Accepted Answer

Blocking and non-blocking aren't really about performance, they are about an interface. If you have a single thread of execution then a blocking call prevents your program from doing any useful work while it's waiting. But if you have multiple threads of execution a blocking call doesn't really matter because you can just leave that thread blocked and do useful work in another.

In Go, a goroutine is swapped out for another one when it blocks on I/O. The Go runtime uses non-blocking I/O syscalls to avoid the operating system blocking the thread so a different goroutine can be run on it while the first is waiting for it's I/O.

Goroutines are really cheap so writing non-blocking style code is not needed.

64
6/25/2011 1:20:25 AM

Write blocking functions. The language allows you to easily turn a synchronous call into an asynchronous one.

If you want to call a function asynchronously, use a go statement. Something like this:

c := make(chan bool)
go func() {
    blockingFunction()
    c <- true
}()

// do some other stuff here while the blocking function runs

// wait for the blocking function to finish if it hasn't already
<-c

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon