Skip to content

Instantly share code, notes, and snippets.

@ostretsov
Last active July 22, 2023 03:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ostretsov/ff18bb21c57edcd19b997906ba10277a to your computer and use it in GitHub Desktop.
Save ostretsov/ff18bb21c57edcd19b997906ba10277a to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"time"
)
func Example_cancellationByTimeout() {
heavyWork := func(d time.Duration) {
timeout := time.After(d)
for i := 0; ; i++ {
time.Sleep(50 * time.Millisecond)
fmt.Println("iteration", i)
select {
case <-timeout:
fmt.Println("timeout")
return
default:
}
}
}
wait := make(chan struct{})
go func() {
heavyWork(70 * time.Millisecond)
close(wait)
}()
<-wait
// Output:
// iteration 0
// iteration 1
// timeout
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment