Golang control Goroutine Start-up and shutdown

Source: Internet
Author: User
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))}

  

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.