How to wait for all goroutines to complete in Go without using time.Sleep?
Hello everyone! I started learning Go and encountered a problem with goroutine synchronization. I'm writing a simple program that launches several goroutines for parallel data processing, but I can't get the main function to wait for them to complete.
Here's my code:
```go
package main
import (
"fmt"
"time"
)
func worker(id int) {
fmt.Printf("Worker %d started\n", id)
time.Sleep(2 * time.Second) // simulating work
fmt.Printf("Worker %d finished\n", id)
}
func main() {
for i := 1; i <= 5; i++ {
go worker(i)
}
// Program exits immediately without waiting for goroutines
fmt.Println("Main function ended")
}
```
The problem is that the program finishes instantly without waiting for the goroutines to execute. I know that you can use `time.Sl