An example of controlling main goroutine exit implementation in Golang concurrent programming

Source: Internet
Author: User

When you use Golang for concurrent programming, when you start a new goroutine asynchronously, the main goroutine does not know if the other goroutine is finished, and once the main goroutine exits, all the goroutine exits. Therefore, you need to control the main goroutine exit time, there are the following methods:

(1) time. Sleep ()

More brutal, not reliable, is to let the main goroutine more run for a while, the actual is not sure whether the other goroutine is run over.

(2) Using channel communication

In the main goroutine has been blocked waiting for an exit signal, after the other Goroutine completed the task to send a signal to the main, the main process received this signal to exit

E: = Make (chan bool)
Go func () {
Fmt. Println ("Hello")
E <-True
}()
<-e

(3) Use sync. Waitgroup

Waitgroup, it can wait until all goroutine execution completes, and blocks the execution of the main thread until all goroutine (the concurrent execution of the Golang) is completed.

 var WG Sync. Waitgroup
     func main () {
          WG. ADD (1)
          go func () {
                FMT. Println ("Hello")
               WG. Done ()//Complete
         } ()
           WG. Wait ()
    }

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.