猿问

停止单个 goroutine 的最佳方法?

在我的程序中,我有几个 go-routines,它们本质上是在运行无穷无尽的进程。为什么?您可能会问,长话短说,这是我整个应用程序的目的,所以改变它是不可能的。我想让用户能够停止单个 go-routine。我知道我可以使用 channel 来通知 go-routines 停止,但是可能有我有 10 个 go-routines 正在运行而我只想停止 1 个的情况。问题是 go-routines 的数量我想运行是动态的并且基于用户输入。对我来说,添加动态停止 go-routine 并允许单打停止的最佳方法是什么?



潇湘沐
浏览 161回答 1
1回答

汪汪一只猫

您需要设计一个地图来管理上下文。假设您已经知道上下文的用法。它可能看起来像:ctx, cancel := context.WithCancel(ctx.TODO())go func(ctx){&nbsp; &nbsp; for {&nbsp; &nbsp; &nbsp; &nbsp; select {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;case <-ctx.Done():&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;default:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // job&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}(ctx)cancel()好的,现在您可以将您的问题转换为另一个问题,它可能称为“如何管理许多 goroutine 的上下文”type GoroutineManager struct{&nbsp; &nbsp; m sync.Map}func (g *GoroutineManager) Add(cancel context.CancelFunc, key string)) {&nbsp; &nbsp; g.m.Store(key, cancel)}func (g *GoroutineManager) KillGoroutine(key string) {&nbsp; &nbsp; cancel, exist := g.m.Load(key)&nbsp; &nbsp; if exist {&nbsp; &nbsp; &nbsp; &nbsp; cancel()&nbsp; &nbsp; }}好的,现在您可以像这样管理您的 goroutine:ctx, cancel := context.WithCancel(ctx.TODO())manager.Add(cancel, "routine-job-1")go func(ctx){&nbsp; &nbsp; for {&nbsp; &nbsp; &nbsp; &nbsp; select {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;case <-ctx.Done():&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;default:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // job&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}(ctx)// kill it as your wishmanager.KillGoroutine("routine-job-1")
随时随地看视频慕课网APP

相关分类

Go
我要回答