【发布时间】: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