🐍 Advanced Python Programming β€” Race ConditionShared State β†’ Interleaving β†’ Synchronization
VLAB THREAD CELL
THREAD SAFETY

See the Collision. Understand the Risk. Protect Shared State.

Two progressive missions using the KASA Python Runtime.

πŸ–₯ Unsafe Shared Counter

Two threads perform read β†’ modify β†’ write on the same value.

Ready.

Race Condition Simulator

Watch both threads read the same value before either writes. One update can be lost.

Shared Counter0
Thread A
idle
Thread B
idle
Press Run & Animate to replay an unsafe interleaving.
Important: a race condition depends on timing/interleaving. A particular run may appear correct; that does not make unsynchronized shared mutation safe.

What should a Python developer know?

Unsafe critical section

READ→MODIFY→WRITE

Multiple threads can interleave this logical operation and overwrite each other's result.

Protected critical section

LOCK→READ/MODIFY/WRITE→UNLOCK

Only one thread enters the protected region at a time.

Mission: repair the counter using threading.Lock and a with lock: critical section. Keep the lock scope as small as practical.
Beyond Lock: reduce shared mutable state when possible. For producer/consumer work, queue.Queue can be a cleaner coordination primitive than manually sharing a list or counter.
Python nuance: do not treat the GIL as a general race-condition solution. Correctness should come from explicit synchronization/design, not assumptions about interpreter scheduling.

πŸ–₯ Thread-Safe Challenge

Complete the TODOs. Target: Expected = 200 and Actual = 200.

Target: Expected: 200 / Actual: 200

πŸ”’ Instructor Solution

PBKDF2-SHA256 (150,000 iterations) + AES-GCM-256.