简体   繁体   English

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

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

To give you context,为了给你上下文,

The variable elementInput is dynamic.变量elementInput是动态的。 I do not know the exact length of it.我不知道它的确切长度。 It can be 10, 5, or etc.它可以是 10、5 等。

The *Element channel type is struct *Element 通道类型为 struct

My example is working.我的例子正在工作。 But my problem is this implementation is still synchronized, because I am waiting for the channel return so that I can append it to my result但我的问题是这个实现仍然是同步的,因为我正在等待通道返回,以便我可以 append 它到我的结果

Can you pls help me how to concurrent call GetElements() function and preserve the order defined in elementInput (based on index)您能帮我如何同时调用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()

Your implementation is not concurrent.您的实现不是并发的。

Reason after every subroutine call you are waiting for result, that is making this serial每次调用您等待结果的子程序后的原因,即制作此序列

Below is Sample implementation similar to your flow以下是类似于您的流程的示例实现

  • calling Concurreny method which calls function concurrently调用同时调用 function 的 Concurreny 方法
  • afterwards we loop and collect response from every above call之后,我们循环并收集上述每个调用的响应
  • main subroutine sleep for 2 seconds主子程序休眠2秒

Go PlayGround with running code -> Sample Application 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