dsshsta97935 2019-05-23 18:34
浏览 24

同时调用许多服务的模式每个都返回值和错误

I'm still experiencing how to make best use of channels. I have 5 outbound service calls (take ~2 min to return), and each gives me a pair of return values. e.g. func serviceCall()(T, error)

I want to make them concurrent, but I find the code very lengthy.

Basically, I have to create 5 channels, 5 structs to hold the return value.

I wrote a simple example to express the scenario, I want to know what is the pattern for this scenario, how I can make this code better.

package main

import (
    "fmt"
    "math/rand"
    "time"
    "log"
)

// goal: run multiple functions concurrently and process the results.
func main() {
now := time.Now()
    // method1
    type res1 struct {
        news string
        err  error
    }
    type res2 struct {
        n   int
        err error
    }

    ch1 := make(chan *res1)
    ch2 := make(chan *res2)

    go func() {
        var res res1
        res.news, res.err = news1()
        ch1 <- &res
    }()

    go func() {
        var res res2
        res.n, res.err = news2()
        ch2 <- &res
    }()

    one := <-ch1
    if one.err != nil {
        log.Fatal(one.err)
    }
    fmt.Println("news1: ", one.news)

    two := <-ch2
    if two.err != nil {
        log.Fatal(two.err)
    }
    fmt.Println("news2: ", two.n)

    fmt.Println("time elapsed: ", time.Since(now))

}

// first sleeps 5 seconds and returns random number or error.
func news1() (string, error) {
    time.Sleep(time.Second * 5)
    return "new1 is here.", nil
}

// second sleeps random seconds and returns random number or error.
func news2() (int, error) {
    n := rand.Intn(20)
    time.Sleep(time.Duration(n) * time.Second)

    return n, nil
}
  • 写回答

2条回答 默认 最新

  • dongtan7351 2019-05-23 18:59
    关注

    As far as I can tell your requirement of 5 service calls outbound is not reflected in the example code that you have written. The example code seems like it will work (I didn't run it to check) but it doesn't cover your use case.

    I would recommend starting smaller with goroutines. This site and linked youtube talk helped me get started understanding how to manage goroutines.

    https://talks.golang.org/2012/concurrency.slide#1

    This video also helped me immensely when I started getting lost in the above talk:

    https://www.youtube.com/watch?v=LvgVSSpwND8

    评论

报告相同问题?

悬赏问题

  • ¥15 关于#网络安全#的问题:求ensp的网络安全,不要步骤要完成版文件
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥20 使用Photon PUN2解决游戏得分同步的问题
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM