Go use context pack to avoid goroutine leaks

Source: Internet
Author: User

Go is a feature that is automatically recycled with memory, so memory is generally not compromised. However, there is a leak in the goroutine, and the leaked goroutine reference memory cannot be recycled.

In the following program, the background goroutine enters the natural number sequence to the pipeline, and the output sequence is in the main function. But when break jumps out of the for loop, the background goroutine is in a state that cannot be reclaimed.

Func Main () {    ch: = func () <-chan int {        ch: = make (chan int)        go func () {for            I: = 0;; i++ {                ch < ;-I            }        } ()        return ch    } () for    V: = Range ch {        FMT. Println (v)        if v = = 5 {break        }}    }

We can avoid this problem through the context package:

Func Main () {    ctx, Cancel: = context. Withcancel (context. Background ())    ch: = func (CTX context. Context) <-chan int {        ch: = make (chan int)        go func () {to            I: = 0;; i++ {                Select {case                <-ctx. Done ():                    return case                ch <-i:                }            }        } ()        return ch    } (CTX) for    V: = Range ch {        Fmt. Println (v)        if v = = 5 {            cancel () Break            }}    }

When the main function jumps out of the loop, it notifies the background goroutine to exit by calling Cancel (), thus avoiding goroutine leaks.

Go use context pack to avoid goroutine leaks

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.