Skip to content

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
Code language: Go (go)

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() }
Code language: Go (go)

See also  Floating-point Approximation in Golang
Tags:
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x