notes-computer-programming-programmingLanguageDesign-prosAndCons-goroutines

" Re: Goroutines

From: John Beshir <john@...>

Date: Mon, 11 Jul 2011 13:25:23 +0100

Just a small correction; goroutines are not "real threads", nor are they traditional "coroutines", but they're much closer to the latter. They are basically coroutines scheduled across an arbitrary number of real threads, with code to yield regularly added to operations like memory allocation, channel send/receive, and system calls.

They are MUCH cheaper than regular threads, their primary cost being 4KB of RAM for the initial segmented stack, and you can easily spawn hundreds of thousands on a single system, more if you have the RAM for it.

Extra real threads are created as necessary when they make blocking system calls, so they behave like real threads, most of the time. Network I/O uses a single thread with non-blocking I/O, which wakes up goroutines when their operation is done, all of which is handled for the programmer, who has a simple blocking I/O interface provided. This means a goroutine per connection makes network code both fast and pretty to write.

This is nothing other languages haven't done in some form, but is significantly cooler than your description suggested, letting you write concurrent code easily and with good performance.

(I should note the GCC implementation currently has a crippled implementation of goroutines which requires an OS thread per goroutine, but this is not the general or intended normal case) "