waitgroup和channel是常见的2种并发控制的方式,而waitgroup只会等待协程的结束而不会主动通知协程结束,这个时候可以使用select + chan 的机制:
1 select+chan,实现主动通知协程退出
var stop chan bool
func reqTask(name string) {
for {
select {
case <-stop:
fmt.Println("stop", name)
return
default:
fmt.Println(name, "send request")
time.Sleep(1 * time.Second)
}
}
}
func main() {
stop = make(chan bool)
go reqTask("worker1")
time.Sleep(3 * time.Second)
stop <- true
time.Sleep(3 * time.Second)
}
更复杂的场景如何做并发控制呢,如子协程开启了子协程,或者需要同时控制多个子协程,这时Context标准库就可以解决这类场景的问题,
而Context的主要功能:
通知子协程退出(正常退出,超时退出)
传递必要的参数
2 Context.withCancel,创建可取消的context
2.1 控制单个Context
func reqTask(ctx context.Context, name string) {
for {
select {
case <-ctx.Done():
fmt.Println("stop", name)
return
default:
fmt.Println(name, "send request")
time.Sleep(1 * time.Second)
}
}
}
func main() {
ctx, cancel := context.WithCancel(context.Background())
go reqTask(ctx, "worker1")
time.Sleep(3 * time.Second)
cancel()
time.Sleep(3 * time.Second)
}
context.withcancel(parent)创建可取消的context,同时返回cancel,
在子协程中,使用select调用 <-ctx.Done()判断是否需要退出
主协程调用cancel函数通知子协程退出
2.2控制多个协程
func main() {
ctx, cancel := context.WithCancel(context.Background())
go reqTask(ctx, "worker1")
go reqTask(ctx, "worker2")
time.Sleep(3 * time.Second)
cancel()
time.Sleep(3 * time.Second)
}
为每个子协程传递相同的上下文ctx即可,调用cancel()函数后该context控制的所有子协程都会退出,
3 context.withValue
type Options struct{ Interval time.Duration }
func reqTask(ctx context.Context, name string) {
for {
select {
case <-ctx.Done():
fmt.Println("stop", name)
return
default:
fmt.Println(name, "send request")
op := ctx.Value("options").(*Options)
time.Sleep(op.Interval * time.Second)
}
}
}
func main() {
ctx, cancel := context.WithCancel(context.Background())
vCtx := context.WithValue(ctx, "options", &Options{1})
go reqTask(vCtx, "worker1")
go reqTask(vCtx, "worker2")
time.Sleep(3 * time.Second)
cancel()
time.Sleep(3 * time.Second)
}
context.withValue()创建一个基于ctx的子Context,并携带了值,
在子协程中,使用ctx.value(key)获取传递的值,读取/修改该值
4 context.WithTimeout
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
go reqTask(ctx, "worker1")
go reqTask(ctx, "worker2")
time.Sleep(3 * time.Second)
fmt.Println("before cancel")
cancel()
time.Sleep(3 * time.Second)
}
WithTimeout()的使用与WithCancel()类似,多了一个参数,用于设置超时时间.
worker2 send request
worker1 send request
worker1 send request
worker2 send request
stop worker2
stop worker1
before cancel
因为超时时间设置为 2s,但是 main 函数中,3s 后才会调用 cancel()
,因此,在调用 cancel()
函数前,子协程因为超时已经退出了
5 context.WithDeadlive
超时退出可以控制子协程的最长执行时间,那 context.WithDeadline()
则可以控制子协程的最迟退出时间。
func reqTask(ctx context.Context, name string) {
for {
select {
case <-ctx.Done():
fmt.Println("stop", name, ctx.Err())
return
default:
fmt.Println(name, "send request")
time.Sleep(1 * time.Second)
}
}
}
func main() {
ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(1*time.Second))
go reqTask(ctx, "worker1")
go reqTask(ctx, "worker2")
time.Sleep(3 * time.Second)
fmt.Println("before cancel")
cancel()
time.Sleep(3 * time.Second)
}
运行结果如下
worker2 send request
worker1 send request
stop worker2 context deadline exceeded
stop worker1 context deadline exceeded
before cancel