In this tutorial, we will delve into the world of Goroutines in Go. Our main goal is to understand what Goroutines are, how they are used, and how to manage them effectively.
By the end of this tutorial, you will learn:
1. What Goroutines are
2. How to create and manage Goroutines
3. How to handle errors and exceptions in Goroutines
4. Best practices for Goroutine usage
Prerequisites:
This tutorial assumes that you have a basic understanding of Go programming language. If you are new to Go, consider going through a beginner's guide or tutorial first.
A Goroutine is a lightweight thread of execution. The term "Goroutine" comes from the word "coroutine", a computer-programming concept that allows multiple entry points for suspending and resuming execution at certain locations.
In Go, Goroutines are used to make asynchronous programming easier and clearer. They are cheaper than threads and their management is abstracted away by the Go runtime, so you won't need to think about thread management or multi-threading programming in general.
To create a Goroutine, we use the go
keyword followed by the function call. Here's an example:
package main
import (
"fmt"
"time"
)
func hello() {
fmt.Println("Hello from goroutine")
}
func main() {
go hello()
time.Sleep(1 * time.Second)
fmt.Println("Hello from main")
}
In this code, go hello()
starts a new Goroutine. Then main
sleeps for 1 second before printing its message.
To manage Goroutines, you can use the sync
package in Go. The WaitGroup
type of sync
package is often used to wait for a collection of Goroutines to finish executing.
package main
import (
"fmt"
"sync"
"time"
)
func worker(id int, wg *sync.WaitGroup) {
defer wg.Done()
fmt.Printf("Worker %d starting\n", id)
time.Sleep(time.Second)
fmt.Printf("Worker %d done\n", id)
}
func main() {
var wg sync.WaitGroup
for i := 1; i <= 5; i++ {
wg.Add(1)
go worker(i, &wg)
}
wg.Wait()
}
In this code, we create 5 worker Goroutines. Each worker is registered to the WaitGroup
using wg.Add(1)
. wg.Wait()
is used to block until all workers finish.
Let's explore some more practical examples:
package main
import (
"fmt"
"time"
)
func say(s string) {
for i := 0; i < 5; i++ {
time.Sleep(100 * time.Millisecond)
fmt.Println(s)
}
}
func main() {
go say("world")
say("hello")
}
In this example, go say("world")
causes a new Goroutine to be created. The main
function runs in its own Goroutine and it runs the say("hello")
function in the main Goroutine. The output will interleave, demonstrating concurrent execution.
Channels provide a way for two Goroutines to communicate with each other and synchronize their execution.
package main
import "fmt"
func sum(a []int, c chan int) {
sum := 0
for _, v := range a {
sum += v
}
c <- sum // send sum to c
}
func main() {
a := []int{7, 2, 8, -9, 4, 0}
c := make(chan int)
go sum(a[:len(a)/2], c)
go sum(a[len(a)/2:], c)
x, y := <-c, <-c // receive from c
fmt.Println(x, y, x+y)
}
Here we’re launching sum
as a Goroutine for each half of our array. sum
sends the sum of a slice of numbers on a channel, which we then print out.
In this tutorial, we have covered the following:
1. What Goroutines are and how they're used in Go.
2. How to create, manage, and synchronize Goroutines.
3. How to handle errors and exceptions in Goroutines.
4. Several practical examples of Goroutine usage.
Now, you should try to use Goroutines in your own projects and see how they can help structure your concurrent code. You can also study more about channels in Go, as they are often used with Goroutines.
Write a program that launches 10 goroutines where each goroutine adds 10 numbers to a channel. Pull the numbers off the channel and print them.
Create a program that generates 100 random numbers. Use goroutines to create a histogram of how many times each number occurs.
Create a program that uses three goroutines to process a batch of jobs concurrently. The jobs, the processing, and the time to process should be represented with random integers.
Remember to use the sync
package to manage and synchronize your Goroutines.
Happy Coding!