繁体   English   中英

在 Go 中,我们如何在保持列表顺序的同时应用并发调用?

[英]In Go, how do we apply concurrency calls while preserving the order of the list?

为了给你上下文,

变量elementInput是动态的。 我不知道它的确切长度。 它可以是 10、5 等。

*Element 通道类型为 struct

我的例子正在工作。 但我的问题是这个实现仍然是同步的,因为我正在等待通道返回,以便我可以 append 它到我的结果

您能帮我如何同时调用GetElements() function 并保留elementInput中定义的顺序(基于索引)

elementInput := []string{FB_FRIENDS, BEAUTY_USERS, FITNESS_USERS, COMEDY_USERS}

wg.Add(len(elementInput))

for _, v := range elementInput {
    //create channel
    channel := make(chan *Element)
    //concurrent call
    go GetElements(ctx, page, channel)
    //Preserve the order

    var elementRes = *<-channel
    if len(elementRes.List) > 0 {
        el = append(el, elementRes)
    }

}

wg.Wait()

您的实现不是并发的。

每次调用您等待结果的子程序后的原因,即制作此序列

以下是类似于您的流程的示例实现

  • 调用同时调用 function 的 Concurreny 方法
  • 之后,我们循环并收集上述每个调用的响应
  • 主子程序休眠2秒

Go PlayGround 与运行代码 ->示例应用程序

func main() {
    Concurrency()
    time.Sleep(2000)
}

func response(greeter string, channel chan *string) {
    reply := fmt.Sprintf("hello %s", greeter)
    channel <- &reply
}


func Concurrency() {
    events := []string{"ALICE", "BOB"}
    channels := make([]chan *string, 0)

    // start concurrently 
    for _, event := range events {
        channel := make(chan *string)
        go response(event, channel)
        channels = append(channels, channel)
    }

    // collect response
    response := make([]string, len(channels))

    for i := 0; i < len(channels); i++ {
        response[i] = *<-channels[i]
    }
   // print response 
    log.Printf("channel response %v", response)
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM