我對 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 關注
- 140 瀏覽
添加回答
舉報
0/150
提交
取消