登录
首页 >  Golang >  Go问答

如何获取 goroutine 的运行结果?

来源:stackoverflow

时间:2024-04-20 22:00:37 196浏览 收藏

IT行业相对于一般传统行业,发展更新速度更快,一旦停止了学习,很快就会被行业所淘汰。所以我们需要踏踏实实的不断学习,精进自己的技术,尤其是初学者。今天golang学习网给大家整理了《如何获取 goroutine 的运行结果?》,聊聊,我们一起来看看吧!

问题内容

在其他语言中,我可以同时运行多个任务并在相应的变量中获取每个任务的结果。

例如在 js 中:

getapi1()
 .then( res => console.debug("result 1: ", res) )

getapi2()
 .then( res => console.debug("result 2: ", res) )

getapi3()
 .then( res => console.debug("result 3: ", res) )

而且我确切地知道哪个函数的执行结果在哪个变量中。

python asyncio 中也是如此:

task1 = asyncio.create_task(getapi1)
task2 = asyncio.create_task(getapi2)
result1 = await task1
result2 = await task2

我是 go 语言的新手。所有指南都说要使用带有 goroutine 的通道。

但是我不明白,当我从频道中读取内容时,如何确定哪个消息与哪个结果匹配?

resultsChan := make(chan map)

go getApi1(resultsChan)
go getApi2(resultsChan)
go getApi3(resultsChan)

for {
 result, ok := <- resultsChan

 if ok == false {
  break
 
 } else {

  // HERE
  fmt.Println(result)  // How to understand which message the result of what API request?
 
 }

}

正确答案


如果同一个通道要将所有 getapin 函数的结果传达给 main,并且您希望以编程方式确定每个结果的来源,则只需向通道元素类型添加专用字段即可。下面,我声明了一个名为 result 的自定义结构类型,其中包含一个名为 orig 的字段,正是出于此目的。

package main

import (
    "fmt"
    "sync"
)

type origin int

const (
    unknown origin = iota
    api1
    api2
    api3
)

type result struct {
    orig origin
    data string
}

func getapi1(c chan result) {
    res := result{
        orig: api1,
        data: "some value",
    }
    c <- res
}

func getapi2(c chan result) {
    res := result{
        orig: api2,
        data: "some value",
    }
    c <- res
}

func getapi3(c chan result) {
    res := result{
        orig: api3,
        data: "some value",
    }
    c <- res
}

func main() {
    results := make(chan result, 3)
    var wg sync.waitgroup
    wg.add(3)
    go func() {
        defer wg.done()
        getapi1(results)
    }()
    go func() {
        defer wg.done()
        getapi2(results)
    }()
    go func() {
        defer wg.done()
        getapi3(results)
    }()
    go func() {
        wg.wait()
        close(results)
    }()
    for res := range results {
        fmt.printf("%#v\n", res)
    }
}

(Playground)

可能的输出(结果的顺序不确定):

8834735538​​17

无论如何,我不会关注wic's suggestion;你的问题根本不是一个很好的反思用例。 As Rob Pike puts it

文中关于的知识介绍,希望对你的学习有所帮助!若是受益匪浅,那就动动鼠标收藏这篇《如何获取 goroutine 的运行结果?》文章吧,也可关注golang学习网公众号了解相关技术文章。

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>