Home > Net >  How to return multiple values from goroutine?
How to return multiple values from goroutine?

Time:09-03

I found some example with "Catch values from Goroutines"-> link

There is show how to fetch value but if I want to return value from several goroutines, it wont work.So, does anybody know, how to do it?

 package main

import (
    "fmt"
    "io/ioutil"
    "log"
    "net/http"
    "sync"
)

// WaitGroup is used to wait for the program to finish goroutines.
var wg sync.WaitGroup

func responseSize(url string, nums chan int) {
    // Schedule the call to WaitGroup's Done to tell goroutine is completed.
    defer wg.Done()

    response, err := http.Get(url)
    if err != nil {
        log.Fatal(err)
    }
    defer response.Body.Close()
    body, err := ioutil.ReadAll(response.Body)
    if err != nil {
        log.Fatal(err)
    }
    // Send value to the unbuffered channel
    nums <- len(body)
}

func main() {
    nums := make(chan int) // Declare a unbuffered channel
    wg.Add(1)
    go responseSize("https://www.golangprograms.com", nums)
    go responseSize("https://gobyexample.com/worker-pools", nums)
    go responseSize("https://stackoverflow.com/questions/ask", nums)
    fmt.Println(<-nums) // Read the value from unbuffered channel
    wg.Wait()
    close(nums) // Closes the channel
    // >> loading forever

Also, this example, worker pools

Is it possible to get value from result: fmt.Println(<-results) <- will be error.

CodePudding user response:

Yes, just read from the channel multiple times:

answerOne := <-nums
answerTwo := <-nums
answerThree := <-nums

Channels function like thread-safe queues, allowing you to queue up values and read them out one by one

P.S. You should either add 3 to the wait group or not have one at all. The <-nums will block until a value is available on nums so it is not necessary

  •  Tags:  
  • go
  • Related