Design Deterministic Concurrent Tests
Core idea
Concurrent tests should coordinate meaningful checkpoints instead of assuming scheduling order. Events establish readiness and permission to continue; barriers align participants. Collect worker exceptions through futures or another explicit channel. Bound waits and release blocked workers in finally. A deterministic test of one interleaving does not prove thread safety for all schedules.
from threading import Eventfrom concurrent.futures import ThreadPoolExecutorready, proceed = Event(), Event()def worker(): ready.set() if not proceed.wait(2): raise TimeoutError('blocked') return 'done'with ThreadPoolExecutor(max_workers=1) as pool: future = pool.submit(worker) try: assert ready.wait(2) print(future.done()) finally: proceed.set() print(future.result(timeout=2))The worker cannot return before permission. The finally block releases it even if the assertion fails.
Expected output:
FalsedonePropagate worker errors
from concurrent.futures import ThreadPoolExecutorimport unittestdef worker(): raise ValueError('invalid job')with ThreadPoolExecutor(max_workers=1) as pool: future = pool.submit(worker) with unittest.TestCase().assertRaisesRegex(ValueError, 'invalid job'): future.result(timeout=2)print('verified')The assertion observes the exception in the test thread, rather than letting a worker failure go unnoticed.
Expected output:
verifiedCommon mistake
A timed join or Future.result timeout does not forcibly stop a worker. Use cooperative release and an outer process timeout for bounded fixtures. Never hold a lock while waiting for a worker that needs it.
Practice
Use a barrier to force both workers to read a counter before either writes. Test the lost update, then rewrite with a lock around the entire update and check the invariant without putting the barrier inside the lock.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Concurrent test design
Check your understanding of concurrent test design.
What is printed?
from threading import Evente=Event(); print(e.is_set()); e.set(); print(e.is_set())What is printed?
from concurrent.futures import ThreadPoolExecutorwith ThreadPoolExecutor(max_workers=1) as p: print(p.submit(sum,[1,2]).result())What makes a checkpoint deterministic?
What does a timeout on result guarantee?