Created
August 24, 2024 10:55
-
-
Save fancellu/e494ec9581b42643b2abff3382ed9ece to your computer and use it in GitHub Desktop.
Golang goroutine channel sync and timeout example
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" | |
"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