Goroutine Ownership and exit

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

The standard implementation of Go Goroutine is not a master. Concurrent. The goal of Unboundedexecutor is to add the concept of ownership to goroutine. You can track the survival of this group of Goroutine by hanging the boot goroutine on a executor. When you need to exit, you can exit these goroutine by using the context cancel method.

 Package ConcurrentImport ("Context""FMT""Time")func Exampleunboundedexecutor_go() {Executor := Newunboundedexecutor()Executor.Go(func(CTX Context.Context) {FMT.Println("ABC")}) Time.Sleep( Time.Second)//OUTPUT:ABC}func Exampleunboundedexecutor_stopandwaitforever() {Executor := Newunboundedexecutor()Executor.Go(func(CTX Context.Context) {Everymillisecond :=  Time.Newticker( Time.Millisecond) for {Select { Case <-CTX. Done():FMT.Println("Goroutine exited")return Case <-Everymillisecond.C://Do something}}}) Time.Sleep( Time.Second)Executor.Stopandwaitforever()FMT.Println("Exectuor stopped")//output://Goroutine exited//Exectuor stopped}

During stop waiting, you can also print the log output where Goroutine has not quit. This need to implement Loginfo this callback.

In addition to providing goroutine ownership. The panic is also recover by default. For the newly launched Goroutine it is very easy to forget to implement defer to recover its panic. Most of the time Goroutine panic behavior should be log down, rather than just hanging off the whole process. The current implementation is to call the global Handlepanic callback.

Implementation code:

Modern-go/concurrent

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.