Passing Data between Go Routines with Channels

· 293 words · 2 minutes read

Go, as a language, makes it very easy to work in parallel on data through its use of go routines (more info on go routines here). However, one of the tricky parts about using go routines is a) to know when they are finished and b) to pass data back from the go routine. Channels make both of these things possible.

In this post we’re only going to look at a basic use case of channels. In the code below we ask the work() function to run on a separate go routine and when it’s finished pass back the string ‘done’ - which will then be printed to screen.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
package main

import (
    "fmt"
)

func main() {

    messages := make(chan string)

    go work(messages)

    msg := <-messages
    fmt.Println("Channel running on", msg)
}

func work(messages chan<- string) {
    messages <- "golangcode.com"
}

You’ll notice that channels are defined with the chan keyword and can be made with make().

In this example, the work function also explicitly states which way the channel it expects will send data. So chan<- will accept data passed into it, and <-chan will expect a channel to pass data out of.

passing data back from a channel in go

Syncronization

In exactly the same way we can achieve syncronization between go routines by using a channel but only sending back a bool to say it’s complete.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
package main

import (
    "fmt"
    "time"
)

func main() {

    isDone := make(chan bool, 1)

    go work(isDone)

    <-isDone
    fmt.Println("Finished")
}

func work(isDone chan bool) {
    fmt.Println("Working...")
    time.Sleep(time.Second)
    isDone <- true
}

sync go routines with channels

Image of Author Edd Turtle

Author:  Edd Turtle

Edd is the Lead Developer at Hoowla, a prop-tech startup, where he spends much of his time working on production-ready Go and PHP code. He loves coding, but also enjoys cycling and camping in his spare time.

See something which isn't right? You can contribute to this page on GitHub or just let us know in the comments below - Thanks for reading!