Hacker News new | ask | show | jobs
by Animats 3554 days ago
Can you write lock-free code in Go without assembly language support? Sometimes you need fence instructions or hardware compare-and-swap.
1 comments

Yes. Portable primitives are provided in the sync.atomic package. They've been careful about the details (eg, inserting fences on architectures like arm). Most applications shouldn't touch this stuff but it's there if you want to try to write a lock free data structure or algorithm.
There are some interesting caveats to using sync.atomic. Some working code on x86_64 did panic on x86_32 since the target struct member was no longer 64-bit aligned.
Yeah. I believe the API docs do call that out. There's not much that can be done about it either, short of forcing 8 byte alignment for all golang objects on 32bit platforms.
Not all, only those that can be proven to be passed to atomic calls.

Given the rejuvenated emphasis on compile performance, it's probably not worthwhile to figure that out :) Overall Go's "don't sugarcoat everything with abstractions" attitude suits me fine for now.

mappu, do you have a need for 64-bit aligned data?

I would be interested if you did. I have a repo that provides a set of packages for doing things like that. If that is a real need I would be interested to add it to the library.

I have a need for quickly aggregating counters across multiple goroutines. `atomic.AddUint64(&central, threadLocal)` works quite well for that, better than pushing to a channel, better than deferring the aggregation until a sync point.

Any needs i have for alignment are derived solely from the requirements of the atomic package.