-2

My basic understanding of a goroutine is that its a simplified way to create a thread.

Looking at the confluent-kafka-go library, the following code is given as an example:

    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)
    }

How does this work though? Would it not just run once and stop working once it looped through all of p.Events() ? How does go know to not abort the goroutine but keep on polling p.Events() - even though it will be empty for most of the times?

lifeofguenter
  • 1,121
  • 1
  • 13
  • 22
  • 1
    "Would it not just run once and stop working once it looped through all of p.Events() ?" That **exactly** is what happens: Once p.Events() is closed the for loop terminates. "How does go know to not abort the goroutine but keep on polling p.Events() - even though it will be empty for most of the times?" Please work through https://tour.golang.org/concurrency/4 ff (or even better the whole Tour). – Volker Apr 27 '20 at 08:21

1 Answers1

4

According to the documentation for Producer.Events(), it returns a channel.

Ranging over a channel only terminates when the channel is closed. See the tour of Go for more details.

Marc
  • 19,394
  • 6
  • 47
  • 51