Skip to content

Instantly share code, notes, and snippets.

@fancellu
Created August 24, 2024 10:55
Show Gist options
  • Save fancellu/e494ec9581b42643b2abff3382ed9ece to your computer and use it in GitHub Desktop.
Save fancellu/e494ec9581b42643b2abff3382ed9ece to your computer and use it in GitHub Desktop.
Golang goroutine channel sync and timeout example
package main
import (
"fmt"
"time"
)
func greet(st string, done chan bool) {
fmt.Println(st)
done <- true
}
func slowGreet(st string, done chan bool) {
time.Sleep(2 * time.Second)
fmt.Println(st)
done <- true
}
func main() {
const doneCount = 4
done := make(chan bool, doneCount)
go greet("Hello", done)
go greet("How are you?", done)
go slowGreet("How...Are...You...?", done)
go greet("Bye", done)
// len of done is 0 here, as no goroutine has finished yet
fmt.Println("len of done is", len(done))
// wait for all goroutines to finish
// we need to wait, else code will exit before output
// coroutines are daemons
for i := 1; i <= cap(done); i++ {
select {
case <-done:
// in case you want to fail if you have hung
// try changing doneCount to 5 to see this in action
case <-time.After(4 * time.Second):
fmt.Println("Timed out waiting for goroutines to complete")
return
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment