How are atomic operations made thread-safe? I've read about the subject in Wikipedia's article on thread-safety. But the article didn't really explain the process behind the scenes. In other words, why can't an "atomic" operation executed by a thread A be interrupted by a thread B?
An atomic operation will either be completed or not done at all. Other threads will not be able to see the operation "in progress" -- it will never be viewed in a partially complete state. This is what the word "atomic" means in this context.
The behind-the-scenes magic for making that true will vary from implementation to implementation. For the purposes of your concurrency design, all you can rely on is that all-or-nothing guarantee on execution.
But they didn't really explain the process behind the scenes, in other words, why an atomic operation executed by a thread A couldn't be interupted by a thread B ?
The reason they don't explain what happens behind the scenes is that that is highly implementation specific. For instance, it depends on the hardware instructions available to do that kind of thing on the implementation platform.
But you shouldn't need to worry about that. You shouldn't care how atomicity (e.g. non-interuptability) is implemented. You should simply rely on the guarantees that are provided by the AtomicXxx class APIs that certain operations will behave in an atomic fashion, and build your higher-level thread safety based on those guarantees.
But note that the atomicity property of AtomicXxx classes only applies to the individual operations. A sequence of AtomicXxx operations will not be performed atomically, and hence won't automatically be thread-safe.
In short, if you use AtomicXxx classes to implement thread-safety, you need to understand what you are doing.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With