Created
September 17, 2018 00:42
-
-
Save jemygraw/bd7784d83f1db57d63fbd0a73f1e0f50 to your computer and use it in GitHub Desktop.
golang context demo
This file contains 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 ( | |
"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