@@ -7,48 +7,59 @@ import (
77 "github.com/ghosind/utils"
88)
99
10- // Race executes the functions asynchronously, it will return the result of the first of the
11- // finished function (including panic), and it will not send a cancel signal to other functions.
12- func Race (funcs ... func (context.Context ) error ) error {
10+ // Race executes the functions asynchronously, it will return the index and the result of the first
11+ // of the finished function (including panic), and it will not send a cancel signal to other
12+ // functions.
13+ func Race (funcs ... func (context.Context ) error ) (int , error ) {
1314 return race (context .Background (), funcs ... )
1415}
1516
16- // RaceWithContext executes the functions asynchronously, it will return the result of the first of
17- // the finished function (including panic), and it will not send a cancel signal to other
18- // functions.
19- func RaceWithContext (ctx context.Context , funcs ... func (context.Context ) error ) error {
17+ // RaceWithContext executes the functions asynchronously, it will return the index and the result
18+ // of the first of the finished function (including panic), and it will not send a cancel signal
19+ // to other functions.
20+ func RaceWithContext (ctx context.Context , funcs ... func (context.Context ) error ) ( int , error ) {
2021 return race (ctx , funcs ... )
2122}
2223
23- // race executes the functions asynchronously, it will return the result of the first of the
24- // finished function (including panic).
25- func race (ctx context.Context , funcs ... func (context.Context ) error ) error {
24+ // race executes the functions asynchronously, it will return the index and the result of the first
25+ // of the finished function (including panic).
26+ func race (ctx context.Context , funcs ... func (context.Context ) error ) ( int , error ) {
2627 if len (funcs ) == 0 {
27- return nil
28+ return - 1 , nil
2829 }
2930
3031 if ctx == nil {
3132 ctx = context .Background ()
3233 }
3334
3435 finished := atomic.Bool {}
35- ch := make (chan error )
36+ ch := make (chan struct {
37+ Index int
38+ Error error
39+ })
3640 defer close (ch )
3741
3842 for i := 0 ; i < len (funcs ); i ++ {
3943 fn := funcs [i ]
44+ n := i
4045
4146 go func () {
4247 err := utils .Try (func () error {
4348 return fn (ctx )
4449 })
4550 if finished .CompareAndSwap (false , true ) {
46- ch <- err
51+ ch <- struct {
52+ Index int
53+ Error error
54+ }{
55+ Index : n ,
56+ Error : err ,
57+ }
4758 }
4859 }()
4960 }
5061
51- err := <- ch
62+ ret := <- ch
5263
53- return err
64+ return ret . Index , ret . Error
5465}
0 commit comments