In this post, we will see how to work with multiple goroutines. If you are looking for the basics, please go through Goroutines in Golang and Channels in Golang.
Multiple Goroutines Simple Example
This code shows how two goroutines will interact when running concurrently. The output order will not be maintained and each time this program is run it may produce a completely new output.
package main
import (
"fmt"
"time"
)
func f(s string) {
for _, c := range s {
fmt.Print(string(c), " ")
time.Sleep(10 * time.Millisecond)
}
}
func main() {
// run two different goroutine
go f("Hello")
go f("World")
// sleep main goroutine
time.Sleep(1 * time.Second)
}
The output is as expected and will look like this.
Nested Goroutines
Now we will see what happens if we nest two goroutines. Goroutines can be nested to an arbitrary depth and the output will be even more random in many cases. Here is an example.
package main
import (
"fmt"
"time"
)
func g(v int) {
fmt.Print(v*2, v*v, " ")
}
func SpawnGoroutines(n int) {
for i := 0; i < n; i++ {
go g(i)
}
}
func main() {
go SpawnGoroutines(10)
// sleep main goroutine
time.Sleep(1 * time.Second)
}
Communication through Channels
Goroutines can communicate via channels. It is a conduit that helps pass information between two goroutines. Here is an example.
package main
import (
"fmt"
"time"
)
func f(ch chan int) {
for i := 0; i < 10; i++ {
// send data to the channel
ch <- i
}
// close the channel
close(ch)
}
func g(ch chan int) {
// loop over the data from the channel
for v := range ch {
fmt.Print(v, " ")
}
}
func main() {
ch := make(chan int)
// send data to the channel
go f(ch)
// receive from the channel
go g(ch)
// sleep main goroutine
time.Sleep(1 * time.Second)
}
As it can be seen channels are the way multiple goroutines communicate.
Further Reading: Golang Mutex