如何停止多个相同的 goroutine 之一

How to stop one of multilpe of the same goroutine

因为很快就会明白,我是 golang n00b。

我有一些基于事件通道启动 goroutines 的代码。假设它启动了 2 个协程,因为我们收到了 2 个 START 类型的事件。

goroutine 以 uri 作为参数启动,这给了我们一些独特之处。

稍后我们收到一个 STOP 类型的事件。

如何停止使用相同 uri 启动的 goroutine?

for {
            select {
            case event := <-eventCh:
                if event.Entry != nil {
                    switch event.Action {
                    case foo.START:
                        log.Println("uri: ", event.Entry.URI)

                        go func(c chan []byte, u string) error{
                            //awesome goroutine code
                        }(myChan, event.Entry.URI)

                    case foo.STOP:
                        log.Println("uri: ", event.Entry.URI)
                        //I'd like to terminate the goroutine that matches event.Entry.URI
                    }
                }
            }
        }

您无法停止 goroutine "from the outside"。您必须向每个 goroutine 传递某种取消信号,并记住它们以供稍后在主 goroutine 中使用。 Context 通常用作取消信号。 goroutine 然后必须检查取消并自动退出:

package main

import (
    "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 code

                // Check ctx.Done or ctx.Err in strategic places and return if done.
                select {
                case <-ctx.Done():
                    return
                default:
                }

                // More awesome goroutine code

                if ctx.Err() != nil {
                    return
                }

                // Even more awesome goroutine code

            }(event.URI)

        case "STOP":
            if cancel, ok := cancels[event.URI]; ok {
                cancel()
                delete(cancels, event.URI)
            }
        }
    }
}