获得最快的戈鲁丁

如何只得到最快的goroutine的结果。例如,我们有这个函数。


func Add(num int)int{

   return num+5

}

我们有这个功能。


func compute(){

  for i := 0; i < 5; i++ {

     go Add(i)

  }

}

我想得到首先完成的goroutine的结果。


慕婉清6462132
浏览 143回答 1
1回答

喵喵时光机

使用 a 获得许多灌浆执行的第一个结果buffered channelfunc Test(t *testing.T) {&nbsp; &nbsp; ch := make(chan int, 1)&nbsp; &nbsp; go func() {&nbsp; &nbsp; &nbsp; &nbsp; for i := 0; i < 5; i++ {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; go func(c chan<- int, i int) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; res := Add(i)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; c <- res&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }(ch, i)&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }()&nbsp; &nbsp; res := <-ch // blocking here, before get first result&nbsp; &nbsp; //close(ch) - writing to close channel produce a panic&nbsp; &nbsp; fmt.Println(res)}PLAYGROUNDPLAYGROUND
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go