1 回答

TA貢獻(xiàn)1898條經(jīng)驗(yàn) 獲得超8個(gè)贊
您需要設(shè)計(jì)一個(gè)地圖來管理上下文。
假設(shè)您已經(jīng)知道上下文的用法。它可能看起來像:
ctx, cancel := context.WithCancel(ctx.TODO())
go func(ctx){
for {
select {
case <-ctx.Done():
return
default:
// job
}
}
}(ctx)
cancel()
好的,現(xiàn)在您可以將您的問題轉(zhuǎn)換為另一個(gè)問題,它可能稱為“如何管理許多 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()
}
}
好的,現(xiàn)在您可以像這樣管理您的 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 關(guān)注
- 112 瀏覽
添加回答
舉報(bào)