Created
July 17, 2019 22:09
-
-
Save ritsz/d255cd8838b18c000c66ea5863b47e5d to your computer and use it in GitHub Desktop.
This file contains hidden or 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 "time" | |
| import "fmt" | |
| import "sync" | |
| func quickping(done chan string, wg* sync.WaitGroup, sec time.Duration) { | |
| defer wg.Done() | |
| time.Sleep( time.Second * sec) | |
| done <- "DONE" | |
| } | |
| func TwoSecTimeOut(done chan string, wg* sync.WaitGroup) { | |
| defer wg.Done() | |
| time.Sleep( time.Second * 2) | |
| done <- "TimeOut" | |
| } | |
| func main() { | |
| var signals [5]chan string | |
| var waiting [5]sync.WaitGroup | |
| for i := range signals { | |
| signals[i] = make(chan string) | |
| defer close(signals[i]) | |
| waiting[i].Add(1) | |
| go quickping(signals[i], &waiting[i], time.Duration(i+2)) | |
| go TwoSecTimeOut(signals[i], &waiting[i]) | |
| } | |
| for i := range signals { | |
| select { | |
| case msg := <- signals[i]: | |
| fmt.Println(msg) | |
| } | |
| } | |
| for i := range signals { | |
| waiting[i].Wait() | |
| } | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
quickPing is a goroutine that returns after arbitrary amount of time.
We have 2 goroutines that write on the same channel and signal the same waitGroup.
So either the quickPing job returns in 2 secs or we get a timeout.