Non blocking code in Go (Part 2)

Written by matzhouse | Published 2016/11/30
Tech Story Tags: programming | golang | software-development

TLDRvia the TL;DR App

Swapping variables in realtime

One process that we see a lot is swapping a config variable for a new one without restarting the running process. Again, we can do this pretty easily with a mutex. Below is some example code that swaps a very simple config struct into an App struct safely with a mutex.

Again we can benchmark it with go test.

Nice and quick, no allocations apart from the obvious initial ones.

Can we make this faster? Well I reckon the answer is yes if we use the atomic package. Something like this..

This bit of code is using one of the Compare and Swap functions available to us — specifically compare and swap pointers.

This basically does the following in an atomic way

IF old version is what we think it isTHEN swap ptr to new version and TRUEELSE false

So how does this perform?

Not too badly. There’s about an 8x speed up over the mutex. There is a slightly simpler version of this that just loads a value into a pointer. The compare and swap algorithm allows you to confirm that nothing has changed at the point of you deciding to set the new variable and the actual setting of the new variable.

I think I should point out here that this bit of code uses the unsafe package to manage some pointer swapping — this isn’t necessarily to everyones taste and it also won’t work in some environments — play.golang.org for example. If you can handle those caveats and if you’re doing a lot of swapping of variables, then it might be a valid performance tweak.

There’s also another interesting struct you can use from the atomic package.

atomic.Value{}

This is a more complete way of pointer swapping, and accepts an interface, meaning you can store and load practically anything. There is one caveat to its use. It must never be copied. Bad things will happen — although to be honest, I don’t know if this is just because you create multiple copies pointing to the same underlying memory, or there’s a specific issue.

Hacker Noon is how hackers start their afternoons. We’re a part of the @AMIfamily. We are now accepting submissions and happy to discuss advertising &sponsorship opportunities.

To learn more, read our about page, like/message us on Facebook, or simply, tweet/DM @HackerNoon.

If you enjoyed this story, we recommend reading our latest tech stories and trending tech stories. Until next time, don’t take the realities of the world for granted!


Published by HackerNoon on 2016/11/30