To synchronize multiple Goroutines to start simultaneously in Go using the sync
package, you can use a sync.WaitGroup
. Here's an example:
package main
import (
"fmt"
"sync"
)
func main() {
// Create a WaitGroup
var wg sync.WaitGroup
// Set the number of Goroutines to wait for
wg.Add(3)
// Start Goroutines
go executeTask(&wg, "Task 1")
go executeTask(&wg, "Task 2")
go executeTask(&wg, "Task 3")
// Wait for all Goroutines to finish
wg.Wait()
fmt.Println("All tasks completed")
}
func executeTask(wg *sync.WaitGroup, taskName string) {
defer wg.Done()
fmt.Printf("Executing %s\n", taskName)
// Simulate some work
// ...
fmt.Printf("%s completed\n", taskName)
}
In this example, we create a sync.WaitGroup
called wg
and set the number of Goroutines to wait for using wg.Add(3)
.
Then, we start three Goroutines using the go
keyword and pass the wg
WaitGroup and the task name to a function called executeTask
.
Inside the executeTask
function, we defer wg.Done()
to notify the WaitGroup that the Goroutine has finished.
After all Goroutines have been started, we call wg.Wait()
to block the main Goroutine until all Goroutines have finished executing. This ensures that all Goroutines start simultaneously.
Finally, after the wg.Wait()
call, we print "All tasks completed" to indicate that all Goroutines have finished their work.
Note: If the number of Goroutines is not known beforehand, you can dynamically add or subtract from the WaitGroup
using wg.Add(1)
and wg.Done()
accordingly.