Created
June 21, 2022 15:50
-
-
Save rahul-yr/c7015fdfdcf7d5f5830a8e2acd0a6c50 to your computer and use it in GitHub Desktop.
Sample addition program with wait groups
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 ( | |
"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