刚开始使用Go时,我在同步多个go例程的响应方面有些挣扎,以便我可以处理结果。
用例
我想同时发出4个带有不同参数的请求。每个响应都包含多个部分。一旦所有请求都被返回,它们将被放入一个数组中。
代码
// Create requests and process them concurrently
responseChannel := make(chan<- response, 100)
for brokerID, request := range requestsByBrokerID {
broker := e.BrokersByBrokerID[brokerID]
go getBrokersPartitionOffsets(broker, request, topicPartitionChannel)
}
func getBrokersPartitionOffsets(broker *sarama.Broker, request *sarama.OffsetRequest, ch chan<- partitionTopicHighWaterMark) {
response, err := broker.GetAvailableOffsets(request)
if err != nil {
broker.Close()
log.Warnf("Cannot fetch offsets from broker %v: %v", broker.ID(), err)
return
}
for topic, partitions := range response.Blocks {
for partitionID, offsetResponse := range partitions {
if offsetResponse.Err != sarama.ErrNoError {
// Shortned...
}
ch <- partitionTopicHighWaterMark{TopicName: topic, PartitionID: partitionID, HighWaterMark: offsetResponse.Offsets[0]}
}
}
}
我的问题
我要等到所有goroutine(从for循环开始)完成后再进行操作。我读到可以关闭该通道,但是我认为这对我没有帮助,因为我有多个使用同一通道的goroutine。我该如何解决这个问题?