Golang Select Exit End Goroutine

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

When multiple threads are enabled, one of the threads terminates the select after the condition has been met, and the other threads will continue to silently run in the background system until the main process shuts down.

To do an experiment and discover that select listener exits will shut down all listening goroutine

Package Mainimport ("FMT"    " Time")varStopBOOL=falseFunc main () {ch:= Make (chanint,0) CH2:= Make (chanint,0) defer func () {Close (ch) close (CH2)} () go func () {ch<-1    }()     forI: =0; I <= -; i++{go func (CH2 Chanint) {             for{fmt. Println (time. Now (). Unix ()) CH2<-1                ifStop {fmt. Println ("Sqlpop Stop")                    return}}} (CH2)}l: for {        Select {         CaseM: = <-ch:fmt. PRINTLN (m) Stop=trueTime . Sleep (time. Second*2)             BreakL Case<-CH2:}} Time. Sleep (time. Second*Ten)}

Output

/data/gopro/src/test/test  [/data/gopro/src/test]14214012391421401239  142140123914214012391421401239142140123914214012391421401239 1421401239 1421401239 1421401239 1421401239 1421401239 1  0.

Originally thought output 1 back to resume printing time but the actual select exits after the rest of the process also exits and does not print until the main session exits

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.