How to create multiple goroutines in Go by example?

Create multiple goroutines in Go by Example

Creating multiple goroutines is a straightforward process. Goroutines are lightweight threads of execution that can run concurrently within a single Go program.

Example

package main

import (
	"fmt"
	"sync"
)

func main() {
	// create a wait group to synchronize the goroutines
	var wg sync.WaitGroup

	// create three goroutines
	for i := 0; i < 3; i++ {
		wg.Add(1)
		go func(id int) {
			defer wg.Done()
			fmt.Printf("Hello from goroutine %d\n", id)
		}(i)
	}

	// wait for all goroutines to finish
	wg.Wait()

	fmt.Println("All goroutines have finished")
}

Output

Hello from goroutine 2
Hello from goroutine 1
Hello from goroutine 0
All goroutines have finished

Explaination

In this example, we create a sync.WaitGroup to synchronize the goroutines. We then create three goroutines using a for loop, and we increment the wait group counter using wg.Add(1) before each goroutine is launched.

Inside each goroutine, we print a message to the console using fmt.Printf(). Note that we pass the i variable as an argument to the goroutine using a closure, to ensure that each goroutine prints its own unique identifier.

Finally, we call wg.Wait() to block the main goroutine until all three goroutines have finished. When all goroutines have finished, we print a message to the console indicating that the program has completed.