Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

I was waiting to see a weird gotcha about multiplication not being atomic or something. Actually, question for people with more low-level knowledge than me: is that solution atomic?


All math operations on your ordinary everyday cpus are equally non–atomic. They read a value, potentially from memory or from cache, operate on it, and leave the result in a register. Then your program probably has to store the result somewhere, or perform more operations on the result. This is why the memcached software has an explicit locking mechanism; any operation on a cached value involves taking a lock, doing the operation, storing the result, and then releasing the lock.


Memcached shouldn't need an explicit lock to add. Unless I'm missing something, you should be able to use atomics.

For example, for adding it should be enough to use an atomic Fetch-And-Add instruction:

https://doc.rust-lang.org/std/sync/atomic/struct.AtomicU32.h...

Multiply doesn't have an equivalent. You can work around that by reading, multiplying and then using CMPXCHG to atomically update the variable if nothing has changed while you were processing. But you need to think about the ABA problem[1]. (I think in this case its safe, but I haven't thought about it enough. Lock free algorithms have subtle bugs.)

[1] https://en.wikipedia.org/wiki/ABA_problem


Is ABA an issue here? "Replace A by X*A" should be perfectly fine if an atomic swap gives you A back, since it means it was actually A at the time when you perform the swap. That it was B a moment go doesn't seem to matter.


Updating an entry in a database table (which is what a memcache entry is, in practice) is not usually as simple as just "change the value from X to Y". Locking is likely necessary no matter what.




Consider applying for YC's Fall 2026 batch! Applications are open till July 27.

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: