Atomic Operations
Concurrency: lesson 8 of 10
Indivisible: nobody sees it half-done.
Lesson 8 of 10 · 4 min
Atomic Operations
Step 1 of 11
counter += 1 looks like one step. The interpreter sees three: read, add, store.
The Idea
An atomic operation cannot be split. Other threads see the world before it or after it, never in between, so no lock is needed. The catch is scope: atomicity covers one step, and most real invariants span several.
Real-World Example
The ticket dispenser at a deli counter. Pulling the tab tears your number and advances the roll in a single motion, so two customers reaching at once still leave with different numbers. Nobody can grab a half-torn 47.
The Code
import itertools, threading
dispenser = itertools.count(1) # next() is one indivisible step
tickets = []
def take(n):
for _ in range(n):
tickets.append(next(dispenser)) # append is atomic too
crowd = [threading.Thread(target=take, args=(50,)) for _ in range(4)]
for person in crowd: person.start()
for person in crowd: person.join()
print(len(tickets), len(set(tickets))) # 200 200 — no number issued twice
Your turn
What does this print?
import itertools
dispenser = itertools.count(1)
served = [next(dispenser) for _ in range(3)]
served.append(next(dispenser))
print(served, len(set(served)))Mini quiz
1 / 3