Go Concurrency

Notes for an excellent video tutorial on Go concurrency-

Goroutines are independently executing function in the same space address (==threads?). using go to initiate the Goroutine, possibly with arguments.

And for communication we use channels with make to exchange messages to/from the goroutine.

*taken from https://blog.golang.org/advanced-go-concurrency-patterns

Wait for all your Goroutines to finish with sync.WaitGroup

wg.Wait() will continue (and finish the program) when the conter of the WaitGroup is zero.

In the example above the Goroutine is anonymous so it has access to the main scope wg variable. I tried it with passing the ref of wg, achieving the same goal without anonymous goroutines.

Using Channels to sync

You can create a channel and send in/out messages of certain pre-defined type. The definition of the channel is chan <type> . fetching a message (blocking until someone is ready to send) is msg:=<-channelName and sending a message through is channelName<-msg (also blocking until someone is ready to receive).

which will output:

→ go run run2.go
cat
sheep
dog
cat

Because both queueing and un-queueing are blocking operations. Goroutinges can be synched with it.

Closing a channel when finished

this will be tricky if you have more than one goroutine to use a channel but a Goroutine may close a channel when it’s finished. using a range channelName you can just iterate over all the messages in a blocking manner until the chhanel is closed. like this:

this example is not very good because i’m creating several Goroutines. And when the first to finish (dog) closes the channel the other Goroutines fails to send messages over it so i’m getting a runtime error:

panic: send on closed channel

Channel with a capacity

Normally, both queueing and un-queueing are blocking. To make it behave differently we may set a buffer size to the channel and the queueing won’t block until the channel is full.

this is ok. another message in the queueu before the un-queueing will block the program

Differrent Channels in the same routine

Two channels may have different speeds you need to handle them (in the same routine). We can handle it with select, that accepts several blocking opeations and performs the first one to be available.

Problem: one channel returns every 0.5s and the other one every 2s. c2 will block c1 messages. So both are printed every 2s and c1 messages are queued up.
fix: use select to execute the first blocking operation

Read-only / Write-only channels

you may declare a channel as readonly with channelName <-chan string

and write-only with channelName chan<- string .