使用context关闭协程以及协程中的协程

2023-06-08,,

package main

import (
"sync"
"context"
"fmt"
"time"
) var wg sync.WaitGroup func worker2(ctx context.Context) {
LOOP:
for {
fmt.Printf("worker2\n")
time.Sleep(time.Second)
select {
case <- ctx.Done():
break LOOP
default:
}
}
} func worker(ctx context.Context) {
go worker2(ctx)
LOOP:
for {
fmt.Printf("worker\n")
time.Sleep(time.Second)
select {
case <- ctx.Done():
break LOOP
default: }
}
wg.Done()
} func main() {
ctx := context.Background()
ctx, cancel := context.WithCancel(ctx)
wg.Add(1)
go worker(ctx)
//time.Sleep(time.Second*3)
cancel()
wg.Wait()
}

使用context关闭协程以及协程中的协程的相关教程结束。

《使用context关闭协程以及协程中的协程.doc》

下载本文的Word格式文档,以方便收藏与打印。