1 回答
TA贡献1898条经验 获得超8个赞
您需要设计一个地图来管理上下文。
假设您已经知道上下文的用法。它可能看起来像:
ctx, cancel := context.WithCancel(ctx.TODO())
go func(ctx){
for {
select {
case <-ctx.Done():
return
default:
// job
}
}
}(ctx)
cancel()
好的,现在您可以将您的问题转换为另一个问题,它可能称为“如何管理许多 goroutine 的上下文”
type GoroutineManager struct{
m sync.Map
}
func (g *GoroutineManager) Add(cancel context.CancelFunc, key string)) {
g.m.Store(key, cancel)
}
func (g *GoroutineManager) KillGoroutine(key string) {
cancel, exist := g.m.Load(key)
if exist {
cancel()
}
}
好的,现在您可以像这样管理您的 goroutine:
ctx, cancel := context.WithCancel(ctx.TODO())
manager.Add(cancel, "routine-job-1")
go func(ctx){
for {
select {
case <-ctx.Done():
return
default:
// job
}
}
}(ctx)
// kill it as your wish
manager.KillGoroutine("routine-job-1")
- 1 回答
- 0 关注
- 160 浏览
添加回答
举报
