When coordinating concurrent work (threads or processes), make “ownership” explicit and authoritative, and ensure every consumer uses the same claimed/produced result.
Apply this in two common patterns:
1) Coalesce duplicate in-flight work (threads)
Example pattern (simplified):
with lock:
cached = cache.get(key)
if cached is not None:
return copy.deepcopy(cached)
inflight = inflight_map.get(key)
if inflight is not None:
event = inflight.event
slot = inflight.slot
# waiter: block for the leader’s publish
else:
event = threading.Event()
slot = [None]
inflight_map[key] = (event, slot)
# leader: run work, then finish
# leader finish (idempotent)
with lock:
if key not in inflight_map and slot[0] is not None:
return payload
slot[0] = copy.deepcopy(payload)
inflight_map.pop(key, None)
event.set()
2) Select and write shared destinations (processes)
.exists() under concurrency.O_CREAT|O_EXCL) and treat that reservation as the source of truth.Checklist