Do not use infinite loops in Golang to check whether Goroutine is completing work

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

When using Goroutine, we often write code like this:

Package Mainimport ("FMT") VAR (flag boolstr  String) func foo () {flag = TRUESTR = "Setup complete!"} Func main () {go foo () for!flag {//) after the execution of Foo () as we intended, flag=true, the loop exits. But in fact this cycle will never quit}fmt. Println (str)}

After running, it is found that the infinite loop in main will never exit, so don't use this infinite polling method to check whether Goroutine has finished the work.


We can use the channel, let Foo () and main () to communicate, let Foo () after the execution of the channel to send a message to main (), tell it that its own things are done, and then main () to continue to do other operations after receiving the message:

Package Mainimport ("FMT") VAR (flag boolstr  String) func foo (ch Chan string) {flag = TRUESTR = "Setup complete!" CH <-"I ' m complete."//foo (): My task is done, send a message to you ~}func main () {ch: = Make (chan string) go foo (CH) <-ch//main (): OK, I got your message. The ~for!flag {}fmt. Println (str)}



If reproduced please specify the source: http://blog.csdn.net/gophers/article/details/24472891




Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

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.