user3591466
user3591466

Reputation: 867

What is the canonical way to control the closing of goroutine if one goroutine is complete?

I have a slice of struct that defines a task, each task is run in a goroutine, and I want all go goroutines to stop whenever the first one complete a task via the signal task.signalComplete

Currently I have the following.

for _, task := range taskList {
    go func(task *myTask, firstCompleteSignal chan<- bool) {
        for {
            select {
                // When the task completes, it emit signalComplete
                case <-task.signalComplete:
                    firstCompleteSignal<-true
                    return
            }
        }

    }(task, firstCompleteSignal)
}

for {
    select {
    case <-firstCompleteSignal:
        // manually stop all go thread
        return
    }
}

Is this canonical?

Or is there library to do this for me like sync.WaitGroup for waiting all goroutine to be done?

Upvotes: 0

Views: 77

Answers (1)

eugenioy
eugenioy

Reputation: 12393

The common idiom is to have a Done channel shared between the calling code and the goroutines.

Then each goroutine would check that channel via a select each time they send a new value to the calling code.

You can find a good example in Go's blog:

https://blog.golang.org/pipelines

(look for "Explicit Cancellation" there)

Later, they incorporated a context package to the standard library, and that is now the most "standard" way to manage cancellation of goroutines.

You can find a good example in the documentation for the package itself:

https://golang.org/pkg/context/#example_WithCancel

Upvotes: 2

Related Questions