Skip to content

Instantly share code, notes, and snippets.

@soerenmartius
Created May 5, 2020 09:40
Show Gist options
  • Save soerenmartius/b43d8103a3f2595aa61336a40eef879b to your computer and use it in GitHub Desktop.
Save soerenmartius/b43d8103a3f2595aa61336a40eef879b to your computer and use it in GitHub Desktop.
Multithreading Example with WaitGroups in Golang
package main
import (
"fmt"
"sync"
"time"
)
func worker(wg *sync.WaitGroup, id int) {
defer wg.Done()
fmt.Printf("Worker %v: Started\n", id)
time.Sleep(time.Second)
fmt.Printf("Worker %v: Finished\n", id)
}
func main() {
var wg sync.WaitGroup
var maxWorkers = 5
for i := 0; i < maxWorkers; i++ {
fmt.Println("Adding worker", i)
wg.Add(1)
go worker(&wg, i)
}
fmt.Printf("Waiting for %d workers to finish\n", maxWorkers)
wg.Wait()
fmt.Println("All Workers Completed")
}
@ZEkme
Copy link

ZEkme commented Mar 20, 2024

great exampel!! Thank u sir!:)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment