Click here to Skip to main content
15,891,864 members
Articles / All Topics

Starting to Use Goroutines

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
24 Jun 2014CPOL 4.3K  
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!

License

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


Written By
Denmark Denmark
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
-- There are no messages in this forum --