O'Reilly logo

Go: Design Patterns for Real-World Projects by Mat Ryer, Mario Castro Contreras, Vladimir Vivien

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Using it all - concurrent singleton

Now that we know how to create Goroutines and channels, we'll put all our knowledge in a single package. Think back to the first few chapter, when we explained the singleton pattern-it was some structure or variable that could only exist once in our code. All access to this structure should be done using the pattern described, but, in fact, it wasn't concurrent safe.

Now we will write with concurrency in mind. We will write a concurrent counter, like the one we wrote in the mutexes section, but this time we will solve it with channels.

Unit test

To restrict concurrent access to the singleton instance, just one Goroutine will be able to access it. We'll access it using channels--the first one to add one, the second ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required