Goroutines

Goroutines are essentially threads. (The name sounds like the older “coroutines,” but those are not independently scheduled like goroutines.) Starting a goroutine is essentially an asynchronous function call: You call the function, but you don't wait for it to return. It starts and runs while the caller continues. Goroutines differ from traditional threads in that they do not expect to be joined; they are detached threads. You always have at least one goroutine: the first one is started by the system to run main.

Goroutines communicate using channels, along which the goroutines send or receive data. The channels are declared with a content type, and they carry a stream of items of that type. The basic channel contains only a single item, so that a sender cannot send a second item until the first has been received. The send will block until the receive occurs. Of course, a receive will block until there is something to receive. This allows channels to be used for synchronization as well as communications.

It is also possible to create channels with a larger capacity, and they will buffer values up to that capacity.

Channels can be used with conventional send or receive operations. Sometimes, though, you have several channels, and want to choose one which will not block. The problem is that if you just pick one and send (or receive), and the operation blocks, your goroutine blocks, even though it could be using a channel that's ready. To deal with this, Go provides the select statement. Select looks a bit like a switch, but it does not compare values. Its cases are send and receive operations, and it selects one to perform that is ready (if any).

Video Lecture