This is a creation in Article, where the information may have evolved or changed.
Recently, when using Golang to do the project, the use of goroutine. It is very convenient to start the process in Golang, just add a go keyword:
Go MyFunc () { //dosomething } ()
But for some long-executed tasks, such as:
Go Loopfunc () { for{ //dosomething repeat } } ()
In some cases, it is inconvenient to exit. For example, you initiate a process that takes a long time to poll for some tasks. In some cases, an external notification is required to actively end the cycle. Found that Golang does not have the Interrupt,stop method of interrupting or shutting down threads like Java. So think of the channel, a similar signal to control the goroutine of the closed exit (actually not really directly shut down the goroutine, just put some long loop blocking function exit, and then let Goroutine himself exit), The specific idea is to register a channel for each goroutine that is launched. To facilitate subsequent use, I encapsulated a simple library: Https://github.com/scottkiss/grtm
The principle is relatively simple, here is not detailed said, directly to see the source code on it. Specific Use examples:
Package Mainimport ( "FMT" "Github.com/scottkiss/grtm" "Time " ) func MyFunc () { fmt. Println ("Do something repeat by interval 4 seconds") Time . Sleep (time. Second * time. Duration (4))}func main () { gm: = Grtm. Newgrmanager () GM. Newloopgoroutine ("MyFunc", MyFunc) FMT. Println ("main function") time . Sleep (time. Second * time. Duration (+)) FMT. Println ("Stop MyFunc goroutine") GM. Stoploopgoroutine ("MyFunc") time . Sleep (time. Second * time. Duration (80))}