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 關注
- 113 瀏覽
添加回答
舉報