我对 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()——即使它在大多数情况下都是空的?
- 1 回答
- 0 关注
- 113 浏览
添加回答
举报
0/150
提交
取消