What does “atomic” mean in programming?

Published on: January 6, 2021

When you're learning about databases or multithreaded programming, it's likely that you'll come across the term "atomic" at some point.

Usually you'll hear the term in the context of an operation. For example, an atomic read / write operation. Or atomic access to a property.

But what does this mean?

Generally, you can summarize atomic as "one at a time".

For example, when accessing or mutating a property is atomic, it means that only one read or write operation can be performed at a time. If you have a program that reads a property atomically, this means that the property cannot change during this read operation.

In Swift, operations on a dictionary are not atomic. This means that in a multithreaded application, a dictionary might be changed from one thread while another thread is reading from it. No thread or operation has exclusive access to your dictionary.

If the operation was atomic, the first read operation would have to finish before the write can start.

Another way to think of an atomic operation is that no observer of an atomic operation can "see" the operation as in-progress. You can observe the operation as not yet started or as completed, but never in between.

I wrote a post about an @Atomic property wrapper that I've seen making the rounds. In that post, you can see why this property wrapper does not guarantee exclusive access properly for value types, resulting in strange results.

If you want to learn more about atomicity and see an example of atomicity in Swift, I highly recommend you give that post a look.

If you're just looking for a definition, think of atomic as exclusive or one at a time. When an operation is performed atomically, you know that no other operations will interfere with your atomic operation.

I hope this quick tip gave you a better idea of what atomic means in programming. If you have any questions about this posts or if you have suggestions to make it better, feel free to reach out on Twitter.

Categories

Quick Tip

Subscribe to my newsletter