Peter
Peter

Reputation: 189

Get the fastest goroutine

How to get only the result of the fastest goroutine. For example let's we have this function.

func Add(num int)int{
   return num+5
}

And we have this function.

func compute(){
  for i := 0; i < 5; i++ {
     go Add(i)
  }
}

I want to get the result of the goroutine that finishes first.

Upvotes: 0

Views: 440

Answers (1)

kozmo
kozmo

Reputation: 4471

Use a buffered channel to get first result of many grouting execution

func Test(t *testing.T) {
    ch := make(chan int, 1)
    go func() {
        for i := 0; i < 5; i++ {
            go func(c chan<- int, i int) {
                res := Add(i)
                c <- res
            }(ch, i)
        }
    }()
    res := <-ch // blocking here, before get first result
    //close(ch) - writing to close channel produce a panic
    fmt.Println(res)
}

PLAYGROUND

It hasn't memory leak when leave a channel open and never close it. When the channel is no longer used, it will be garbage collected.

Upvotes: 1

Related Questions