shad-go/lectures/05-concurrency/context/cancelation/cancelation.go

47 lines
660 B
Go
Raw Normal View History

2020-04-02 11:42:31 +00:00
package cancelation
import (
"context"
"time"
)
func SimpleCancelation() {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
go func() {
time.Sleep(5 * time.Second)
cancel()
}()
if err := doSlowJob(ctx); err != nil {
panic(err)
}
}
2020-04-02 14:01:16 +00:00
// OMIT
2020-04-02 11:42:31 +00:00
func SimpleTimeout() {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := doSlowJob(ctx); err != nil {
panic(err)
}
}
2020-04-02 14:01:16 +00:00
// OMIT
2020-04-02 11:42:31 +00:00
func doSlowJob(ctx context.Context) error {
for {
select {
case <-ctx.Done():
return ctx.Err()
default:
// perform a portion of slow job
time.Sleep(1 * time.Second)
}
}
}
// OMIT