How to Stop a Goroutine in Golang


It’s possible to stop a Goroutine by sending a value into it via a signal channel:

exit := make(chan bool)
go func() {
    for {
        select {
        case <- exit:
            return
        default:
            // Perform some tasks
        }
    }
}()

// Exit the Goroutine
exit <- true

As an alternative, you could also use a WaitGroup and range over it:

package main
import (
    "fmt"
    "sync"
)
func main() {
    var wg sync.WaitGroup
    c := make(chan bool)
    wg.Add(1)
    go func() {
        defer wg.Done()
        for b := range c {
            fmt.Printf("Hello %t\n", b)
        }
    }()
    c <- true
    c <- true
    close(c)
    wg.Wait()
}