这个 goroutine 是如何连续 运行 (它是如何工作的)?

How does this goroutine continuously run (how is it working)?

我对 goroutine 的基本理解是它是一种创建线程的简化方法。

查看confluent-kafka-go库,以下代码为例:

    go func() {
        for e := range p.Events() {
            switch ev := e.(type) {
            case *kafka.Message:
                if ev.TopicPartition.Error != nil {
                    fmt.Printf("Delivery failed: %v\n", ev.TopicPartition)
                } else {
                    fmt.Printf("Delivered message to %v\n", ev.TopicPartition)
                }
            }
        }
    }()

    // Produce messages to topic (asynchronously)
    topic := "myTopic"
    for _, word := range []string{"Welcome", "to", "the", "Confluent", "Kafka", "Golang", "client"} {
        p.Produce(&kafka.Message{
            TopicPartition: kafka.TopicPartition{Topic: &topic, Partition: kafka.PartitionAny},
            Value:          []byte(word),
        }, nil)
    }

这是如何工作的?它不会只是 运行 一次并在遍历所有 p.Events() 后停止工作吗? go 如何知道不中止 goroutine 而是继续轮询 p.Events() - 即使它在大多数时候都是空的?

根据documentation for Producer.Events(),它returns一个频道。

仅当频道关闭时,对频道的测距才会终止。有关详细信息,请参阅 tour of Go