Skip to content

Instantly share code, notes, and snippets.

@debedb
Created November 25, 2022 20:32
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 debedb/4b9a22033b9de5ed5ae68dabe7d86b2b to your computer and use it in GitHub Desktop.
Save debedb/4b9a22033b9de5ed5ae68dabe7d86b2b to your computer and use it in GitHub Desktop.
Go: Contexts
package main
import (
"context"
"fmt"
"sync"
"time"
)
func withCancel() {
var wg sync.WaitGroup
ctx, cancel := context.WithCancel(context.Background())
go func() {
ch := ctx.Done()
defer wg.Done()
fmt.Println("Done: ", <-ch)
}()
go func() {
defer wg.Done()
d, _ := time.ParseDuration("100ms")
fmt.Printf("Will manually cancel in %s\n", d)
time.Sleep(d)
cancel()
}()
wg.Add(2)
wg.Wait()
}
func withTimeout() {
var wg sync.WaitGroup
d, _ := time.ParseDuration("100ms")
fmt.Printf("Will auto-cancel in %s\n", d)
ctx, _ := context.WithTimeout(context.Background(), d)
go func() {
ch := ctx.Done()
defer wg.Done()
fmt.Println("Done: ", <-ch)
}()
wg.Add(1)
wg.Wait()
}
func main() {
withCancel()
withTimeout()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment