Click here to Skip to main content
Click here to Skip to main content
Technical Blog

Tagged as

Starting to use Goroutines

, 24 Jun 2014 CPOL
Rate this:
Please Sign up or sign in to vote.
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

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:

<script src="https://gist.github.com/mbanzon/8b7fb8935d213ff1bf4c.js"></script>

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:

<script src="https://gist.github.com/mbanzon/c5b447ecb5337e84124f.js"></script>

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:

<script src="https://gist.github.com/mbanzon/0311e9828ad1b3ec172a.js"></script>

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!

License

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

Share

About the Author

Michael Banzon

Denmark Denmark
No Biography provided

Comments and Discussions

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