Created
May 5, 2020 09:40
-
-
Save soerenmartius/b43d8103a3f2595aa61336a40eef879b to your computer and use it in GitHub Desktop.
Multithreading Example with WaitGroups in Golang
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
great exampel!! Thank u sir!:)