Skip to content

Instantly share code, notes, and snippets.

@jemygraw
Created September 17, 2018 00:42
Show Gist options
  • Save jemygraw/bd7784d83f1db57d63fbd0a73f1e0f50 to your computer and use it in GitHub Desktop.
Save jemygraw/bd7784d83f1db57d63fbd0a73f1e0f50 to your computer and use it in GitHub Desktop.
golang context demo
package main
import (
"context"
"fmt"
"sync"
"time"
)
func main() {
wg := sync.WaitGroup{}
ctx, cancelFunc := context.WithCancel(context.Background())
for i := 1; i <= 10; i++ {
name := fmt.Sprintf("work%d", i)
wg.Add(1)
go func() {
defer wg.Done()
work(ctx, name)
}()
}
<-time.After(time.Second * 10)
cancelFunc()
//wait for all the work done
wg.Wait()
}
func work(ctx context.Context, name string) {
for {
select {
case <-ctx.Done():
//quit the work when done() fired
fmt.Println("break", name)
return
default:
<-time.After(time.Second * 1)
}
fmt.Println(name, time.Now().String())
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment