Click here to Skip to main content
12,896,108 members (60,819 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as


Posted 24 Jun 2014

Starting to Use Goroutines

, 24 Jun 2014 CPOL
Rate this:
Please Sign up or sign in to vote.
Starting to use Goroutines

One of the key features of Go is goroutines.

All it takes to run code concurrently is to prefix a function call with the word go and like magic – it runs concurrently!

Concurrency introduces problems with synchronization – which is a common question when starting to program in Go. Check out the following example here.

When run, it will look like this:

mbanzon$ go run goroutine_ex1.go
Nothing left to do.

Which is a little awkward. The reason that neither of the two goroutines seems to run is that the main function doesn’t wait for running goroutines – so the program just exits.

The time package can be used to add a delay like this.

Which will cause the code to pause for one second. The output is now as expected:

mbanzon$ go run goroutine_ex2.go
Hello from goroutine #1
Hello from goroutine #2
Nothing left to do.

But there is one problem – the execution time will be one second AND if either of the goroutines actually do something – something that takes longer than a second – it will not get to finish.

Behold: sync.WaitGroup!

By using the sync.WaitGroup, you can count a number of running goroutines and wait for them to finish, like this.

This will return the expected:

mbanzon$ go run goroutine_wg.go
Hello from goroutine #1
Hello from goroutine #2
Nothing left to do.

And the runtime is no longer than needed!


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Michael Banzon
Denmark Denmark
No Biography provided

You may also be interested in...


Comments and Discussions

-- There are no messages in this forum --
Permalink | Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.170424.1 | Last Updated 25 Jun 2014
Article Copyright 2014 by Michael Banzon
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid