Golang channels tutorial


December 6, 2013

Golang has built-in instruments for writing concurrent programs. Placing a go statement before a function call starts the execution of that function as an independent concurrent thread in the same address space as the calling code. Such thread is called goroutine in Golang. Here I should mention that concurrently doesn’t always mean in parallel. Goroutines are means of creating concurrent architecture of a program which could possibly execute in parallel in case the hardware allows it. There is a great talk on that topic Concurrency is not parallelism.

Let’s start with an example of a goroutine:

  1. func main() {
  2. // Start a goroutine and execute println concurrently
  3. go println("goroutine message")
  4. println("main function message")
  5. }

This program will print main function message and possibly goroutine message. I say possibly because spawning a goroutine has some peculiarities. When you start a goroutine the calling code (in our case it is the main function) doesn’t wait for a goroutine to finish, but continues running further. After calling a printlnthe main function ends its execution and in Golang it means stopping of execution of the whole program with all spawned goroutines. But before it happens our goroutine could possibly finish executing its code and print the goroutine message string.

As you understand there must be some way to avoid such situations. And for that there are channels in Golang.

Channels basics

Channels serve to synchronize execution of concurrently running functions and to provide a mechanism for their communication by passing a value of a specified type. Channels have several characteristics: the type of element you can send through a channel, capacity (or buffer size) and direction of communication specified by a <- operator. You can allocate a channel using the built-in function make:

  1. i := make(chan int) // by default the capacity is 0
  2. s := make(chan string, 3) // non-zero capacity
  3. r := make(<-chan bool) // can only read from
  4. w := make(chan<- []os.FileInfo) // can only write to

Channels are first-class values and can be used anywhere like other values: as struct elements, function arguments, function returning values and even like a type for another channel:

  1. // a channel which:
  2. // - you can only write to
  3. // - holds another channel as its value
  4. c := make(chan<- chan bool)
  5. // function accepts a channel as a parameter
  6. func readFromChannel(input <-chan string) {}
  7. // function returns a channel
  8. func getChannel() chan bool {
  9. b := make(chan bool)
  10. return b
  11. }

For writing and reading operations on channel there is a <- operator. Its position relatively to the channel variable determines whether it will be a read or a write operation. The following example demonstrates its usage, but I have to warn you that this code does not work for some reasons described later:

  1. func main() {
  2. c := make(chan int)
  3. c <- 42 // write to a channel
  4. val := <-c // read from a channel
  5. println(val)
  6. }

Now, as we know what channels are, how to create them and perform basic operations on them, let’s return to our very first example and see how channels can help us.

  1. func main() {
  2. // Create a channel to synchronize goroutines
  3. done := make(chan bool)
  4. // Execute println in goroutine
  5. go func() {
  6. println("goroutine message")
  7. // Tell the main function everything is done.
  8. // This channel is visible inside this goroutine because
  9. // it is executed in the same address space.
  10. done <- true
  11. }()
  12. println("main function message")
  13. <-done // Wait for the goroutine to finish
  14. }

This program will print both messages without any possibilities. Why? done channel has no buffer (as we did not specify its capacity). All operations on unbuffered channels block the execution until both sender and receiver are ready to communicate. That’s why unbuffered channels are also called synchronous. In our case the reading operation <-done in the main function will block its execution until the goroutine will write data to the channel. Thus the program ends only after the reading operation succeeds.

In case a channel has a buffer all read operations succeed without blocking if the buffer is not empty, and write operations - if the buffer is not full. These channels are called asynchronous. Here is an example to demonstrate the difference between them:

  1. func main() {
  2. message := make(chan string) // no buffer
  3. count := 3
  4. go func() {
  5. for i := 1; i <= count; i++ {
  6. fmt.Println("send message")
  7. message <- fmt.Sprintf("message %d", i)
  8. }
  9. }()
  10. time.Sleep(time.Second * 3)
  11. for i := 1; i <= count; i++ {
  12. fmt.Println(<-message)
  13. }
  14. }

In this example message is a synchronous channel and the output of the program is:

  1. send message
  2. // wait for 3 seconds
  3. message 1
  4. send message
  5. send message
  6. message 2
  7. message 3

As you see after the first write to the channel in the goroutine all other writing operations on that channel are blocked until the first read operation is performed (about 3 seconds later).

Now let’s provide a buffer to out message channel, i.e. the creation line will look asmessage := make(chan string, 2). This time the output will be the following:

  1. send message
  2. send message
  3. send message
  4. // wait for 3 seconds
  5. message 1
  6. message 2
  7. message 3

Here we see that all writing operations are performed without waiting for the first read for the buffer of the channel allows to store all three messages. By changing channels capacity we can control the amount of information being processed thus limiting throughput of a system.


Now let’s get back to our not working example with read/write operations.

  1. func main() {
  2. c := make(chan int)
  3. c <- 42 // write to a channel
  4. val := <-c // read from a channel
  5. println(val)
  6. }

On running you’ll get this error (details will differ):

  1. fatal error: all goroutines are asleep - deadlock!
  2. goroutine 1 [chan send]:
  3. main.main()
  4. /fullpathtofile/channelsio.go:5 +0x54
  5. exit status 2

The error you got is called a deadlock. This is a situation when two goroutines wait for each other and non of them can proceed its execution. Golang can detect deadlocks in runtime that’s why we can see this error. This error occurs because of the blocking nature of communication operations.

The code here runs within a single thread, line by line, successively. The operation of writing to the channel (c <- 42) blocks the execution of the whole program because, as we remember, writing operations on a synchronous channel can only succeed in case there is a receiver ready to get this data. And we create the receiver only in the next line.

To make this code work we should had written something like:

  1. func main() {
  2. c := make(chan int)
  3. // Make the writing operation be performed in
  4. // another goroutine.
  5. go func() {
  6. c <- 42
  7. }()
  8. val := <-c
  9. println(val)
  10. }

Range channels and closing

In one of the previous examples we sent several messages to a channel and then read them. The receiving part of code was:

  1. for i := 1; i <= count; i++ {
  2. fmt.Println(<-message)
  3. }

In order to perform reading operations without getting a deadlock we have to know the exact number of sent messages (count, to be exact), because we cannot read more then we sent. But it’s not quite convenient. It would be nice to be able to write more general code.

In Golang there is a so called range expression which allows to iterate through arrays, strings, slices, maps and channels. For channels, the iteration proceeds until the channel is closed. Consider the following example (does not work for now):

  1. func main() {
  2. message := make(chan string)
  3. count := 3
  4. go func() {
  5. for i := 1; i <= count; i++ {
  6. message <- fmt.Sprintf("message %d", i)
  7. }
  8. }()
  9. for msg := range message {
  10. fmt.Println(msg)
  11. }
  12. }

Unfortunately this code does not work now. As was mentioned above the range will work until the channel is closed explicitly. All we have to do is to close the channel with a close function. The goroutine will look like:

  1. go func() {
  2. for i := 1; i <= count; i++ {
  3. message <- fmt.Sprintf("message %d", i)
  4. }
  5. close(message)
  6. }()

Closing a channel has one more useful feature - reading operations on closed channels do not block and always return default value for a channel type:

  1. done := make(chan bool)
  2. close(done)
  3. // Will not block and will print false twice
  4. // because it’s the default value for bool type
  5. println(<-done)
  6. println(<-done)

This feature may be used for goroutines synchronization. Let’s recall one of our examples with synchronization (the one with done channel):

  1. func main() {
  2. done := make(chan bool)
  3. go func() {
  4. println("goroutine message")
  5. // We are only interested in the fact of sending itself,
  6. // but not in data being sent.
  7. done <- true
  8. }()
  9. println("main function message")
  10. <-done
  11. }

Here the done channel is only used to synchronize the execution but not for sending data. There is a kind of pattern for such cases:

  1. func main() {
  2. // Data is irrelevant
  3. done := make(chan struct{})
  4. go func() {
  5. println("goroutine message")
  6. // Just send a signal "I'm done"
  7. close(done)
  8. }()
  9. println("main function message")
  10. <-done
  11. }

As we close the channel in the goroutine the reading operation does not block and the main function continues to run.

Multiple channels and select

In real programs you’ll probably need more than one goroutine and one channel. The more independent parts are - the more need for effective synchronization. Let’s look at more complex example:

  1. func getMessagesChannel(msg string, delay time.Duration) <-chan string {
  2. c := make(chan string)
  3. go func() {
  4. for i := 1; i <= 3; i++ {
  5. c <- fmt.Sprintf("%s %d", msg, i)
  6. // Wait before sending next message
  7. time.Sleep(time.Millisecond * delay)
  8. }
  9. }()
  10. return c
  11. }
  12. func main() {
  13. c1 := getMessagesChannel("first", 300)
  14. c2 := getMessagesChannel("second", 150)
  15. c3 := getMessagesChannel("third", 10)
  16. for i := 1; i <= 3; i++ {
  17. println(<-c1)
  18. println(<-c2)
  19. println(<-c3)
  20. }
  21. }

Here we have a function that creates a channel and spawns a goroutine which will populate the channel with three messages in a specified interval. As we see the third channel c3 has the least interval, thus we except its messages to appear prior to others. But the output will be the following:

  1. first 1
  2. second 1
  3. third 1
  4. first 2
  5. second 2
  6. third 2
  7. first 3
  8. second 3
  9. third 3

Obviously we got a successive output. That is because the reading operation on the first channel blocks for 300 milliseconds for each loop iteration and other operations must wait. What we actually want is to read messages from all channels as soon as they are any.

For communication operations on multiple channels there is a select statement in Golang. It’s much like the usual switch but all cases here are communication operations (both reads and writes). If the operation in case can be performed than the corresponding block of code executes. So, to accomplish what we want, we have to write:

  1. for i := 1; i <= 9; i++ {
  2. select {
  3. case msg := <-c1:
  4. println(msg)
  5. case msg := <-c2:
  6. println(msg)
  7. case msg := <-c3:
  8. println(msg)
  9. }
  10. }

Pay attention to the number 9: for each of the channels there were 3 writing operations, that’s why I have to perform 9 loops of the select statement. In a program which is meant to run as a daemon there is a common practice to run select in an infinite loop, but here I’ll get a deadlock if I’ll run one.

Now we get the expected output, and non of reading operations block others. The output is:

  1. first 1
  2. second 1
  3. third 1 // this channel does not wait for others
  4. third 2
  5. third 3
  6. second 2
  7. first 2
  8. second 3
  9. first 3


Channels is a very powerful and interesting mechanism in Golang. But in order to use them effectively you have to understand how they work. In this article I tried to explain the very necessary basics. For further learning I recommend you look at the following:

ft_authoradmin  ft_create_time2018-12-25 10:57
 ft_update_time2018-12-25 11:04