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 member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.