Goroutines are lightweight threads in the Go language, managed by the Go runtime environment. They are more efficient than traditional threads, allowing tens of thousands of Goroutines to run concurrently on a single or few operating system threads.
What is Goroutine?
Goroutines are started using the go keyword in Go, allowing functions or methods to run concurrently within the same address space. Each Goroutine consumes minimal memory, which enables the creation of thousands of Goroutines. In contrast, traditional threads consume more memory, limiting their scalability.
gopackage main import ( "fmt" "time" ) func say(s string) { for i := 0; i < 5; i++ { time.Sleep(100 * time.Millisecond) fmt.Println(s) } } func main() { go say("world") say("hello") }
In the above code, go say("world") starts a new Goroutine. This means say("world") and say("hello") run concurrently.
How to Stop Goroutines?
In Go, there is no native method to directly terminate or stop a Goroutine. To stop a Goroutine, the common approach is to use a channel to send a signal to it, indicating when to stop execution.
gopackage main import ( "fmt" "time" ) func cleanup() { fmt.Println("Doing some cleaning...") } func worker(stopCh <-chan bool) { for { select { case <-stopCh: cleanup() return default: fmt.Println("working...") time.Sleep(500 * time.Millisecond) } } } func main() { stopCh := make(chan bool) go worker(stopCh) time.Sleep(2 * time.Second) stopCh <- true fmt.Println("Stopped worker!") }
In this example, the worker function runs in a loop, listening for signals on the stopCh channel using the select statement. When a signal is received from stopCh, it calls the cleanup function to perform cleanup and returns to stop the Goroutine's execution. This method allows Goroutines to stop gracefully through cooperation, avoiding resource leaks or inconsistent states that might occur with forced termination.