您无法从外部停止goroutine。您必须将某种取消信号传递给每个goroutine,并记住它们,以备以后在main
goroutine中使用。甲上下文通常被用作一个消除信号。然后,goroutine必须检查取消并自动退出:
package mainimport ( "context")type Event struct { Action string URI string}func main() { var eventCh chan Event ctx := context.Background() cancels := make(map[string]context.CancelFunc) // Maps URIs to cancellation functions. for event := range eventCh { switch event.Action { case "START": if cancels[event.URI] != nil { panic("duplicate URI: " + event.URI) } ctx, cancel := context.WithCancel(ctx) cancels[event.URI] = cancel defer cancel() // cancel must always be called to free resources. go func(u string) { // Awesome goroutine pre // Check ctx.Done or ctx.Err in strategic places and return if done. select { case <-ctx.Done(): return default: } // More awesome goroutine pre if ctx.Err() != nil { return } // Even more awesome goroutine pre }(event.URI) case "STOP": if cancel, ok := cancels[event.URI]; ok { cancel() delete(cancels, event.URI) } } }}


