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.
Previous Article
Golang Tutorials
- Hello World
- Operators in Go
- Declarations in Go
- Values in Go
- Variables in Go
- For in Go
- If/Else in Go
- Switch in Go
- Arrays in Go
- Slices in Go
- Maps in Go
- Range in Go
- Functions in Go
- Closures in Go
- Recursion in Go
- Pointers in Go
- Strings and Runes in Go
- Structs in Go
- Methods in Go
- Interfaces in Go
- Generics in Go
- Errors in Go
- Goroutines in Go
- Channels in Go
- Select in Go
- Timeouts in Go
- Timers in Go
- Worker Pools in Go
- WaitGroups in Go
- Mutexes in Go
- Sorting in Go
- Panic in Go
- Defer in Go
- Recover in Go
- JSON in Go
- XML in Go
- Time in Go
- Epoch in Go
- Time Formatting in Go
- Random Numbers in Go
- Number Parsing in Go
- URL Parsing in Go
- SHA256 Hashes in Go
- Base64 Encoding in Go
- Reading Files in Go
- Writing Files in Go
- File Paths in Go
- Directories in Go
- Testing and Benchmarking in Go
- Command-Line Arguments in Go
- Command-Line Flags in Go
- Command-Line Subcommands in Go
- Environment Variables in Go
- HTTP Client in Go
- HTTP Server in Go
- Context in Go
- Signals in Go