Signaling shutdown

To demonstrate the problem, let's start with a simple goroutine demo; we'll launch three threads that print progress. For each thread, we'll print Started followed by . until the thread stops, at which point Ended will be printed:

package main

import (
"fmt"
"time"
)

func tick() {
fmt.Println("Started")

for _ = range time.NewTicker(time.Second).C {
fmt.Print(".")
}

fmt.Println("Ended")
}

func main() {
go tick()
go tick()
go tick()

time.Sleep(5 * time.Second)
}

If you run this code, you'll see the following output. The threads start and tick as expected and, after a 5 second timeout, the program exits. No Ended messages are seen:

The output of unterminated goroutines

As you can see from this simple demo, the goroutines aren't gracefully terminated; they simply stop running. If we're writing complex data, sending a message to a remote server, or waiting for an important response, this would probably result in data corruption or other unexpected results. Let's look at how to signal goroutines to stop when our application terminates.

We start by creating a simple channel called stop that's passed into each goroutine. When the application is ready to exit, we'll signal each thread so it can finish its work by closing this channel. We update the tick function to check whether this new channel is closed and if so, it'll exit. To allow the code to complete before the application exits, we must add a new pause at the end of main() for the cleanup. The updated code looks like this:

package main

import (
"fmt"
"time"
)

func tickUntil(stop chan(struct{})) {
fmt.Println("Started")

ticker := time.NewTicker(time.Second).C
for {
select {
case <-ticker:
fmt.Print(".")
case <-stop:
fmt.Println("Ended")
return
}
}
}

func main() {
stop := make(chan(struct{}))

go tickUntil(stop)
go tickUntil(stop)
go tickUntil(stop)

time.Sleep(5 * time.Second)
close(stop)

time.Sleep(10 * time.Millisecond)
}

Running this should display the following output, which is what we were looking for in the first place:

With a signal channel, our threads can end just before the program exits
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.220.152.139