Skip to content

Instantly share code, notes, and snippets.

@rahul-yr
Created June 21, 2022 15:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rahul-yr/c7015fdfdcf7d5f5830a8e2acd0a6c50 to your computer and use it in GitHub Desktop.
Save rahul-yr/c7015fdfdcf7d5f5830a8e2acd0a6c50 to your computer and use it in GitHub Desktop.
Sample addition program with wait groups
package main
import (
"log"
"sync"
"time"
)
// wg is a wait group
// it is used to wait for all go routines to finish
var wg sync.WaitGroup
// addTwoNumbers adds two numbers together and prints the result
func addTwoNumbers(a int, b int) {
// update the wait group counter to indicate that the go routine is done
defer wg.Done()
// sleep for a second to simulate a long running operation
time.Sleep(2 * time.Second)
log.Println("Result:", a+b)
}
// main is the entry point for the program
func main() {
// add as many go routines as you want to run concurrently
// and then wait for them to finish
wg.Add(1)
// call addTwoNumbers with two numbers
go addTwoNumbers(1, 2)
// wait for all go routines to finish
wg.Wait()
log.Println("Done")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment