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

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
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:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
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()
}