Skip to content

Instantly share code, notes, and snippets.

@arschles

arschles/ctx.go

Created Aug 26, 2016
Embed
What would you like to do?
Golang 1.7 Contexts
package main
import (
"context"
"log"
"net/http"
"sync"
"time"
)
const (
numLoops = 10
runTime = 5 * time.Second
)
func runLoop(ctx context.Context, wg *sync.WaitGroup, i int) {
start := time.Now()
defer wg.Done()
for {
select {
case <-ctx.Done():
log.Printf("Loop %d done after %s", i, time.Now().Sub(start))
return
default:
}
log.Printf("Loop %d lives on. It's been %s since start", i, time.Now().Sub(start))
time.Sleep(1 * time.Second)
}
}
func main() {
// set up the contexts
rootCtx := context.Background()
start := time.Now()
ctx, cancelFn := context.WithTimeout(rootCtx, runTime)
defer cancelFn()
log.Printf("Starting %d loop(s), running for %s", numLoops, runTime)
var wg1 sync.WaitGroup
for i := 0; i < numLoops; i++ {
wg1.Add(1)
go runLoop(ctx, &wg1, i)
}
wg1.Wait()
log.Printf("All %d are done after %s", numLoops, time.Now().Sub(start))
log.Printf("\n\n///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\n")
log.Printf("Starting HTTP server for cancellation")
ctx, cancelFn = context.WithCancel(rootCtx)
var wg2 sync.WaitGroup
start = time.Now()
for i := 0; i < numLoops; i++ {
wg2.Add(1)
go runLoop(ctx, &wg2, i)
}
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
cancelFn()
wg2.Wait()
log.Printf("All %d loops done after %s, after being cancelled by the HTTP request", numLoops, time.Now().Sub(start))
w.WriteHeader(http.StatusOK)
})
http.ListenAndServe(":8080", nil)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.