stuzer05 hat die Gist bearbeitet . Zu Änderung gehen
1 file changed, 23 insertions
main.go(Datei erstellt)
@@ -0,0 +1,23 @@ | |||
1 | + | func doWork(ctx context.Context) { | |
2 | + | for { | |
3 | + | select { | |
4 | + | case <-ctx.Done(): | |
5 | + | return | |
6 | + | default: | |
7 | + | } | |
8 | + | ||
9 | + | time.Sleep(1 * time.Second) | |
10 | + | fmt.Println("doing work...") | |
11 | + | } | |
12 | + | } | |
13 | + | ||
14 | + | func main() { | |
15 | + | bgCtx := context.Background() | |
16 | + | innerCtx, cancel := context.WithCancel(bgCtx) | |
17 | + | ||
18 | + | go doWork(innerCtx) // call goroutine | |
19 | + | time.Sleep(3 * time.Second) // do work in main | |
20 | + | ||
21 | + | // well, if `doWork` is still not done, just cancel it | |
22 | + | cancel() | |
23 | + | } |
Neuer
Älter