【问题标题】:How does this goroutine continuously run (how is it working)?这个 goroutine 如何连续运行(它是如何工作的)?
【发布时间】:2020-04-27 07:45:20
【问题描述】:

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

【问题讨论】:

  • “它会不会只运行一次并在遍历所有 p.Events() 后停止工作?” 正是 发生了什么:一旦 p.Events() 关闭,for 循环就会终止。 “go 怎么知道不中止 goroutine 而是继续轮询 p.Events() - 即使它在大多数情况下都是空的?”请通过tour.golang.org/concurrency/4 ff 工作(或者甚至更好地完成整个巡回赛)。

标签: go kafka-producer-api goroutine librdkafka


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-27
    • 2021-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-27
    相关资源
    最近更新 更多