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.
|
|
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.
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.
|
|