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.