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

问题描述 投票:0回答:1

我对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()-即使在大多数情况下它都是空的?

我对goroutine的基本理解是,它是创建线程的简化方法。以confluent-kafka-go库为例,给出以下代码:go func(){...

go kafka-producer-api goroutine librdkafka
1个回答
1
投票

根据documentation for Producer.Events(),它返回一个通道。

© www.soinside.com 2019 - 2024. All rights reserved.