Skip to content

Instantly share code, notes, and snippets.

@ritsz
Created July 17, 2019 22:09
Show Gist options
  • Select an option

  • Save ritsz/d255cd8838b18c000c66ea5863b47e5d to your computer and use it in GitHub Desktop.

Select an option

Save ritsz/d255cd8838b18c000c66ea5863b47e5d to your computer and use it in GitHub Desktop.
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()
}
}
@ritsz
Copy link
Author

ritsz commented Jul 17, 2019

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment