Stopping goroutines?

Hi

i have to invoke goroutuine /thread from a loop. Because of the loop, there are many go routines executes in parallel. If any routine/thread executed successfully, then i have to stop all other thread/routine.

Is there any way to implement this?

There are several ways to implement this depending on what your goroutine is doing - keep in mind that a goroutine can’t be “killed” like a unix process. It has to be signalled to stop in some way. Can you describe what your goroutines will be doing? Making API calls? Running long computation? Running an infinite (or very large) loop? Something else?

@maroux . The loop executes in finite number of times and go routine makes API calls.

I have to stop all other go routine execution,if any go routines executes successfully. ie. API returns successfully

@sumith using context is the right way to do this:

func doCalls() {
    ctx, cancel := context.WithCancel(context.Background())
    defer cancel()
    wg := sync.WaitGroup{}
    for _ := range numGoRoutines {
        wg.Add(1)
        go func() {
            defer cancel()
            defer wg.Done()
            client := http.Client{}
            client.Do(ctx, ...)
        }()
    }
    wg.Wait()
}

@maroux , Go routines executes for the last index only.
i.e numGoRoutines is 4. excutes only for last index ( 3).

func apiCalls(ctx context) {
client := http.Client{}
client.Do(ctx, …)
}

func doCalls() {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
wg := sync.WaitGroup{}
for _ := range numGoRoutines {
wg.Add(1)
go func() {
defer cancel()
defer wg.Done()
apiCalls() //–
}()
}
wg.Wait()
}

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.