Created
July 22, 2023 03:05
-
-
Save ostretsov/14f36c4879bc63bdaabdb57e5c4b6ac4 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 ( | |
"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