diff --git a/waitgroups/go.mod b/waitgroups/go.mod new file mode 100644 index 0000000..f6e92bf --- /dev/null +++ b/waitgroups/go.mod @@ -0,0 +1,3 @@ +module waitgroups + +go 1.23.1 diff --git a/waitgroups/main.go b/waitgroups/main.go new file mode 100644 index 0000000..088b5e5 --- /dev/null +++ b/waitgroups/main.go @@ -0,0 +1,29 @@ +package main + +import ( + "fmt" + "math/rand" + "sync" + "time" +) + +var numberList = []int{1, 2, 3, 4, 5} + +func main() { + var a sync.WaitGroup + + for _, v := range numberList { + a.Add(1) + go func() { + defer a.Done() + worker(v) + }() + } + a.Wait() +} + +func worker(id int) { + fmt.Printf("Worker %v is starting\n", id) + time.Sleep(time.Duration(rand.Intn(10) * int(time.Second))) + fmt.Printf("Worker %v is done\n", id) +}