Skip to main content
6 day streak
Skip to lesson
CareerPetalPython field guide
Loading progress...
Course contents
PYTHON FIELD GUIDE

Course contents 72 topics / 15 parts

Full course overviewOriginal coding practice / separate server checks

Essentials first, then internals and engineering trade-offs.

LESSON 38 / CONCURRENCY AND ASYNC

Threads, races and lock ownership

Make shared-state transitions safe without assuming the GIL solves them.

AdvancedTutorial 14 min core+12 min deep divePython 3.11+ / 2026-10-27
Saved work unavailable

Save privately stores your edited code, notes and current section. Runs and public checks are not saved as verified scores.

Before you start

Learners ready to reason about Python internals, resource boundaries and the listed prerequisites.

Explore the connected curriculum and preparation map

Lesson content version 2026-10-27. Suggested core budget: 14 minutes; optional deep dive: 12 more minutes. These are reading/practice estimates, not a timed test.

Suggested preparation and repair routes

If an example or checkpoint feels unclear, revisit the relevant foundation and return. These links do not lock the lesson or claim you passed a prerequisite.

Actual runtime and local-lab boundaries

Browser Python 3.13: fresh isolated worker, 4-second execution, 16 KiB output, 256 MiB Python heap; no outbound network, host processes, interactive input or package installation.

Real host threads and scheduling are not certified by the browser runtime. Use the local lab for actual threading; labelled models remain conceptual.

Public checks, revealed answers and project self-checks are learning feedback, not verified mastery or problem acceptance. Saving code does not execute it.

YOU WILL BE ABLE TO
  • Explain a multi-step update is a contract
  • Apply locks protect invariants, not individual lines
  • Reason about deadlocks and cancellation
01

A multi-step update is a contract

Threads are paths of execution inside one process. They can share objects, so a decision based on an old value can become wrong before the write happens. Protect the whole decision, not just the final assignment.

READ / UNDERSTAND / THEN EXPERIMENT

Understand first

A booking service must not promise one seat to two callers. Read variables, if statements and assignment first. The shared seat count is only part of the promise: the number of accepted bookings must also agree with it.

Words you will see

Thread
One execution path within a process, normally sharing that process's memory.
Race condition
A result that depends on the relative progress of competing operations.
Invariant
A rule that must stay true across an entire state transition.

The wrong number can look reasonable

seen_a and seen_b deliberately save the same starting value, 1. Each comparison therefore succeeds. Both writes use a saved value rather than the newest seats value. The final zero hides the error: two accepted bookings have consumed one seat.

The statements stand for steps that real threads could interleave. This is a counterexample to an unsafe design, not a probability estimate or an actual parallel run. A single observed successful threaded run would not remove this counterexample.

Choose who owns the decision

When several threads share seats, all paths that read, check and change it must use the same synchronization rule. A lock can make that entire operation exclusive. Another design sends booking requests to one owner that updates its private state in order.

Use threads for suitable overlapping I/O, not because sharing objects is automatically easy. If there are no requests, nothing changes; if there are no seats, every positive booking must be rejected. Browser WebAssembly does not promise OS threads: use this model there, and a supported local CPython installation for a real threading lab.

The original example, step by step

These steps explain the original code below. They do not change when you edit your own experiment.

  1. seen_a = seats

    A takes a snapshot of the one seat.

  2. seen_b = seats

    B takes the same snapshot before either modeled write.

  3. accepted_b = seen_b > 0

    B accepts based on the saved one, not A's later decision.

  4. seats = seen_b - 1

    B overwrites the count with zero, concealing the double acceptance.

Read, check and write operations can interleave across threads. The GIL in conventional CPython does not make every compound application operation atomic. Design ownership first: avoid sharing mutable state when possible, and protect a complete invariant when sharing is necessary.

A deliberately chosen interleaving model, not an observed thread trace

Conceptual reasoning steps for the original example, not a live trace of your edited Python.

  1. Read twiceA and B both observe one available seat.
  2. Decide twiceEach accepts its booking using that old observation.
  3. Write twiceBoth store zero; the counter looks valid but two bookings were accepted.
Predict before you run

Why does zero not prove this booking was safe?

Two stale seat decisionsPYTHON 3

Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

Preparing the editor controls. Run and editing become available when this page is interactive.

Browser Python limits

Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

Change one thing; explain the difference.

Start with no seats.

Try: Change seats = 1 to seats = 0.

Both flags become False and the count stays zero.

Let B read after A writes.

Try: Move seen_b and accepted_b below A's if block.

B now sees zero and rejects. One safe schedule does not make the original shared design safe.

Before you move on

Start with two seats and let three callers all save 2 before any write. What does this model accept and store?

Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.

Read a worked answer

It accepts all three and each stores 1. The valid-looking final count does not match three acceptances. The decision and write must share one protected lifetime.

This is a self-check, not a required quiz or a saved score. You can revisit any concept.
02

Locks protect invariants, not individual lines

A lock lets one cooperating caller own a critical section at a time. The critical section must include every step needed to keep the shared promise true.

READ / UNDERSTAND / THEN EXPERIMENT

Understand first

A reservation changes available seats and the acceptance count together. Testing a small sequential transition makes the business rule visible before adding scheduling. Know dictionary indexing and return values; synchronization is an extra layer around this rule.

Words you will see

Lock
A synchronization object that grants exclusive entry to cooperating callers.
Critical section
The code that runs while holding a lock.
Contention
Waiting caused by several callers wanting the same protected resource.

Make the protected region complete

The fixture accepts a request for two seats from three, leaving one. The second request cannot fit and returns False without changing either field. In a threaded version, put the comparison, both updates and the decision under the same lock used by every caller.

Use with lock so leaving the block, including by exception, releases the lock. A lock around only state['seats'] -= amount would be too late: two callers could already have passed the comparison. The acceptance counter belongs to the same invariant.

Keep the region small without splitting the rule

Validate public input before the shared transition; this fixture assumes positive integer amounts. Do slow network calls outside the lock if they are not part of the atomic decision. Calling a slow service inside can make every other booking wait and can introduce dependency cycles.

A single owner with queued messages can be easier to reason about than many lock users. An immutable snapshot is useful for readers, but a snapshot alone does not coordinate writers. This browser-safe fixture is not a lock implementation and provides no safety if called concurrently without protection.

The original example, step by step

These steps explain the original code below. They do not change when you edit your own experiment.

  1. if amount <= state['seats']:

    Decide against the current count.

  2. state['seats'] -= amount

    Consume seats only on acceptance.

  3. state['accepted'] += 1

    Record the same accepted operation.

  4. print(reserve(state, 2))

    The two calls print True then False because only one request fits.

Use with lock to release even after an exception. Keep critical sections small but complete. Define a consistent lock acquisition order when multiple locks are involved; waiting on I/O while holding a lock can create contention or deadlock.

Predict before you run

After both requests, how many acceptances are recorded?

A whole reservation transitionPYTHON 3

Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

Preparing the editor controls. Run and editing become available when this page is interactive.

Browser Python limits

Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

Change one thing; explain the difference.

Make the second request fit.

Try: Change the second reserve(state, 2) to reserve(state, 1).

Both accept; seats becomes zero and accepted becomes two.

Try a too-large first request.

Try: Change the first request to 4.

That request leaves state untouched; the later request for two can still succeed.

Before you move on

If one seat remains, may a request for two increment accepted before returning False?

Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.

Read a worked answer

No. A rejected request must leave both fields unchanged. Protecting a counter increment does not repair the wrong business transition.

This is a self-check, not a required quiz or a saved score. You can revisit any concept.
03

Update a shared counter

The shared-counter lab uses one real lock for every increment, then waits for all workers before reading the result. It demonstrates lock ownership, not a promised thread order or speedup.

READ / UNDERSTAND / THEN EXPERIMENT

Understand first

This preserved original program is a local OS-thread lab. Save it as counter_lab.py and run python counter_lab.py with supported CPython 3.11+. The bounded Docker verifier also runs it with real threads. Browser WebAssembly may reject threading; that error must stay visible rather than being replaced by 20.

Words you will see

Executor
An object that manages workers and submitted jobs.
Future
A handle representing one job's eventual result or exception.
Join
Wait for owned work to finish before proceeding.

One owner for each increment

The lock and state are created once outside increment. Each worker enters with lock, changes count and exits. The underscore parameter means the mapped input is not used; the twenty input values request twenty increments.

pool.map schedules calls, and list consumes its results so worker exceptions can be observed. The executor's with block waits for its workers on exit. print is afterwards, so no outstanding increment is omitted from the final reading.

What this lab does and does not establish

Both workers may compete for the same lock, but their print order is not tested because they do not print. Twenty successful increments yield 20 even if one worker happens to do most of them. The program does not measure overlap, fairness, timing or parallel CPU execution.

For a small counter, sequential code is simpler and usually avoids needless overhead. Use this lab to study ownership, then use an event or barrier for carefully controlled race experiments instead of arbitrary sleeps. Never infer that removing the lock is safe because a particular run still displays 20.

The original example, step by step

These steps explain the original code below. They do not change when you edit your own experiment.

  1. lock = Lock()

    Create the single synchronization object shared by all workers.

  2. with lock:

    Acquire it for an increment and release it on block exit.

  3. list(pool.map(increment, range(20)))

    Submit twenty calls and consume their results.

  4. print(state['count'])

    Read only after the executor has finished its owned work.

All counter updates use the same lock and the executor is joined before reading the final result. No thread-order output is assumed.

Predict before you run

Which line observes the final state after worker shutdown?

Update a shared counterPYTHON 3

Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

Preparing the editor controls. Run and editing become available when this page is interactive.

Browser Python limits

Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

Change one thing; explain the difference.

Submit five increments.

Try: Replace range(20) with range(5).

The expected final count is 5, regardless of which worker executes each call.

Use one worker.

Try: Set max_workers=1 and retain twenty inputs.

The count stays 20; this is not evidence that two workers made it faster.

Before you move on

If the lab uses range(7) and three workers, what count is guaranteed if every call succeeds?

Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.

Read a worked answer

Seven. Worker count changes the available execution paths, not the number of submitted increments. No worker order or timing is guaranteed.

This is a self-check, not a required quiz or a saved score. You can revisit any concept.
DETAILED WALKTHROUGH / NOT JUST A SUMMARY

Where this idea earns its place

Threads help coordinate suitable concurrent work in one process, often blocking I/O. They also share memory, which makes ownership and synchronization part of correctness. A program that works during one run may simply have experienced a fortunate interleaving; absence of a reproduced race is not evidence that a compound transition is atomic.

Follow the mechanism step by step

A read-check-write sequence spans several operations. Another thread can act between them even under conventional CPython's GIL assumptions. A lock protects the entire invariant when every participating path uses it consistently. with lock releases on exceptional exit, but does not decide which operations belong inside the protected region.

Work through a concrete application

For a capacity counter, protect checking available capacity and claiming it in one critical section. If check and increment use separate acquisitions, both callers can pass the check. Keep expensive I/O outside the lock only when doing so preserves the state contract, and define recovery if work fails after capacity was reserved.

Failure cases and misleading shortcuts

Holding lock A while waiting for work that needs A can deadlock. Inconsistent ordering of multiple locks creates another common cycle. Cancelling a Future usually cannot forcibly stop arbitrary already-running thread code. Do not assume the GIL makes native extensions, free-threaded builds or multi-step domain operations behave identically.

Cost, ownership and alternatives

Lock contention can serialize an otherwise concurrent workload. More threads can increase memory, scheduling overhead and pressure on downstream services. Use a bounded pool and measure representative latency/throughput. CPU-bound Python work may need another execution model, depending on interpreter build and native-library behaviour.

Verify the contract

Use events or barriers to coordinate relevant interleavings in tests rather than arbitrary sleeps. Assert the invariant after all workers are joined. Test exception paths for released locks and reserved resources, and test shutdown with pending work. A deterministic final count is useful evidence but does not cover every application transition.

Transfer question: How would you reduce deadlock risk when two locks are needed?

Define and consistently follow a global acquisition order, minimize overlapping lifetimes and avoid waiting for external work while holding locks. Document the order and inspect all paths, including callbacks and cleanup, since one reversed path can recreate a cycle.

RECALL BEFORE YOU SCROLL

Can you explain it?

Try from memory. Feedback stays on this page and does not award judged progress.

Does the conventional CPython GIL make every read-check-write sequence safe?
TRANSFER THE IDEA

Rebuild: Update a shared counter

Without copying the worked code, reproduce its observable contract: All counter updates use the same lock and the executor is joined before reading the final result. No thread-order output is assumed. Then change one boundary input and explain the result.

Your practice starterPYTHON 3

Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

Preparing the editor controls. Run and editing become available when this page is interactive.

Browser Python limits

Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

MAKE THE RULE WORK ON NEW INPUTS

Guided practice and transfer

These are public local learning checks, not certified scores. Edited code is saved only with Save work and place. Run results are not stored as certified scores. Export useful unsaved work before leaving.

A short function primer before you begin

def names a reusable rule. The input names in parentheses are parameters. Indent its body; replace the starter's pass placeholder. The body runs when called, not when defined.

return hands a value back and ends that call. print only displays a value. The public assert checks call your function with fresh fixtures; a false condition raises AssertionError with its message.

Return a value, do not only print itPYTHON 3

Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

Preparing the editor controls. Run and editing become available when this page is interactive.

Browser Python limits

Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

GUIDED PRACTICE

Guided: make each reservation one transition

Implement reserve_units(stock, requests). Model a single state owner accepting requests in order, never approving more units than remain.

The contract

  • stock is a nonnegative exact integer. requests is a finite list of nonnegative exact integers. Other input types and negative request amounts are outside this exercise's domain.
  • Return an exact tuple (remaining, decisions): remaining is an exact int; decisions is a fresh list of exact bool values in request order. Zero requests are accepted even at zero stock.
  • Accept an amount if amount <= remaining, then subtract it. Reject without changing remaining otherwise. Preserve repeated requests and never mutate requests.
  • Empty requests returns (stock, []). This is a deterministic state-policy function, not a thread-safe reservation service or a WebAssembly threading claim.
Guided: make each reservation one transitionPYTHON 3

Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

Preparing the editor controls. Run and editing become available when this page is interactive.

Browser Python limits

Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

Inspect 6 public checks

Transparent local learning checks, not exhaustive or tamper-proof grading.

  1. accept then reject
    out = reserve_units(3, [2, 2])
    assert type(out) is tuple and len(out) == 2 and type(out[0]) is int and out == (1, [True, False])
    assert type(out[1]) is list and all(type(flag) is bool for flag in out[1])
  2. empty is a fresh decision list
    a = reserve_units(4, [])
    b = reserve_units(4, [])
    assert type(a) is tuple and a == (4, []) and b == a and type(a[1]) is list and a[1] is not b[1]
  3. zero amount at zero stock
    out = reserve_units(0, [0, 1, 0])
    assert type(out) is tuple and out == (0, [True, False, True]) and all(type(flag) is bool for flag in out[1])
  4. repeated requests remain distinct
    out = reserve_units(2, [1, 1, 1])
    assert type(out) is tuple and out == (0, [True, True, False]) and type(out[0]) is int
  5. oversized request leaves stock
    out = reserve_units(5, [6, 5])
    assert type(out) is tuple and out == (0, [False, True]) and all(type(flag) is bool for flag in out[1])
  6. input and result ownership
    requests = [2, 0, 3]
    out = reserve_units(5, requests)
    assert type(out) is tuple and out == (0, [True, True, True]) and requests == [2, 0, 3] and out[1] is not requests
    out[1].append(False)
    assert requests == [2, 0, 3] and reserve_units(5, [2, 0, 3]) == (0, [True, True, True])
    Why does this pure policy not make a shared threaded service safe by itself?

    A real shared owner must protect the whole read/check/write transition or serialize requests. The loop is O(n) time and O(n) result space for n requests; no scheduling safety is established by its output.

    GUIDED PRACTICE

    Guided: agree on one resource order

    Implement ordered_locks(pairs) to plan one lexicographic acquisition order for all resource names mentioned in requested pairs.

    The contract

    • pairs is a finite list of two-string tuples. Strings identify resources; repeated pairs, repeated resource names and empty strings are allowed.
    • Return an exact tuple of distinct names in Python's case-sensitive lexicographic order. Empty input returns (). Do not mutate pairs.
    • Include both ends, including a resource paired with itself. This is a planning model only: no locks are acquired and no actual deadlock freedom is tested.
    • A real system needs every acquisition path to follow the same order and map each name to the same lock object.
    Guided: agree on one resource orderPYTHON 3

    Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

    Preparing the editor controls. Run and editing become available when this page is interactive.

    Browser Python limits

    Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

    Inspect 6 public checks

    Transparent local learning checks, not exhaustive or tamper-proof grading.

    1. opposite requests share one order
      out = ordered_locks([('stock', 'cash'), ('cash', 'stock')])
      assert type(out) is tuple and out == ('cash', 'stock')
    2. empty plan
      out = ordered_locks([])
      assert type(out) is tuple and out == ()
    3. self-pair is acquired once
      out = ordered_locks([('a', 'a')])
      assert type(out) is tuple and out == ('a',)
    4. include both pair endpoints
      out = ordered_locks([('z', 'a'), ('m', 'z')])
      assert type(out) is tuple and out == ('a', 'm', 'z')
    5. case-sensitive and empty names
      out = ordered_locks([('b', 'A'), ('', 'a')])
      assert type(out) is tuple and out == ('', 'A', 'a', 'b')
    6. preserve caller order
      pairs = [('z', 'b'), ('a', 'z'), ('z', 'b')]
      out = ordered_locks(pairs)
      assert type(out) is tuple and out == ('a', 'b', 'z') and pairs == [('z', 'b'), ('a', 'z'), ('z', 'b')]
      Why can a sorted plan still fail to prevent a real deadlock?

      A caller might ignore it, use a different lock identity or wait on work needing a held lock. For p pairs and u unique names this planner uses O(p + u log u) expected time with ordinary set assumptions and O(u) extra space.

      TRANSFER / TRY BEFORE OPENING HINTS

      Transfer: preserve a two-account invariant

      Implement transfer_balances(balances, moves). The requirement changes from one stock count to paired debit/credit updates whose combined total must stay fixed.

      The contract

      • balances is a dict from string account names to nonnegative exact integer amounts. moves is a finite list of (source, target, amount) tuples, with string names and nonnegative exact integer amounts.
      • Return a fresh exact dict. Process moves in order. Apply a move only if both names exist and source has at least amount; otherwise leave both balances unchanged.
      • A move from an existing account to itself is a no-op, including when its amount is larger than its balance. Unknown accounts never get created. Zero amounts and repeated moves are allowed.
      • Do not mutate balances or moves. Empty moves returns an equal but separate dict. This models an atomic business rule; real concurrent debit/credit requires shared synchronization or a transactional owner.
      Transfer: preserve a two-account invariantPYTHON 3

      Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

      Preparing the editor controls. Run and editing become available when this page is interactive.

      Browser Python limits

      Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

      Inspect 6 public checks

      Transparent local learning checks, not exhaustive or tamper-proof grading.

      1. debit and credit together
        out = transfer_balances({'a': 5, 'b': 1}, [('a', 'b', 3)])
        assert type(out) is dict and out == {'a': 2, 'b': 4} and all(type(v) is int for v in out.values())
      2. empty moves copy ownership
        balances = {'a': 0}
        out = transfer_balances(balances, [])
        assert type(out) is dict and out == balances and out is not balances
        out['a'] = 7
        assert balances == {'a': 0}
      3. reject overdraft without partial update
        out = transfer_balances({'a': 2, 'b': 0}, [('a', 'b', 3), ('a', 'b', 2)])
        assert type(out) is dict and out == {'a': 0, 'b': 2}
      4. unknown accounts are not invented
        out = transfer_balances({'a': 4}, [('a', 'missing', 2), ('missing', 'a', 1)])
        assert type(out) is dict and out == {'a': 4}
      5. self zero and repeated moves
        out = transfer_balances({'a': 2, 'b': 0}, [('a', 'a', 99), ('a', 'b', 0), ('a', 'b', 1), ('a', 'b', 1), ('a', 'b', 1)])
        assert type(out) is dict and out == {'a': 0, 'b': 2}
      6. preserve inputs and total
        balances = {'a': 3, 'b': 2}
        moves = [('a', 'b', 2), ('b', 'a', 1)]
        out = transfer_balances(balances, moves)
        assert type(out) is dict and out == {'a': 2, 'b': 3} and out is not balances and sum(out.values()) == 5
        assert balances == {'a': 3, 'b': 2} and moves == [('a', 'b', 2), ('b', 'a', 1)]
        What changed from reserving one stock counter?

        A successful transition now updates two owners together while conserving a total. A real shared implementation needs both resources protected in a common order. With b accounts and m moves, the model takes O(b + m) expected time and O(b) result space under ordinary dictionary lookup assumptions.

        A GOOD PLACE TO PAUSE

        Core route complete.

        If you can explain the checkpoint and attempt the practice, move on. Come back for the deep dive when you want the why behind the how.

        Save your core reading milestone

        GIL caveats

        The global interpreter lock, or GIL, is an execution rule of conventional CPython, not a lock on your business invariant. It does not promise that several statements form one indivisible operation.

        READ / UNDERSTAND / THEN EXPERIMENT

        Understand first

        A reviewer may say a Python update needs no synchronization because of the GIL. Separate the interpreter's execution mechanism from the application's multi-step promise. Read the core stale-seat example first; this optional model makes the mismatch numeric.

        Words you will see

        GIL
        The global interpreter lock used by conventional CPython to restrict execution of much Python code.
        CPU-bound
        Work whose main limiting resource is computation rather than waiting for I/O.
        Free-threaded build
        An optional CPython build that changes the conventional GIL assumptions.

        A runtime mechanism cannot decide your invariant

        Both snapshots equal five. Each request for four passes against its own snapshot, and both store one. Eight approved units expose the broken rule even though balance is not negative. The example is deliberately sequential so its outcome is portable.

        Conventional CPython serializes much bytecode execution, but releases the GIL around suitable I/O and some native operations. Precise switching and atomicity details depend on interpreter and version. Do not rely on an observed bytecode sequence as an application synchronization contract.

        Choose execution tools from measured work

        Threads can overlap waiting for independent I/O. CPU-heavy pure Python may need processes, optimized native code or a different algorithm instead. Optional free-threaded builds change performance and synchronization assumptions; they do not make stale application decisions correct.

        Benchmark the actual implementation and workload outside this deterministic fixture. A serial baseline is essential; adding workers can increase overhead. Empty work has nothing to accelerate, and neither this model nor the real counter lab establishes CPU scaling.

        The original example, step by step

        These steps explain the original code below. They do not change when you edit your own experiment.

        1. snapshots = [balance, balance]

          Save two observations of five.

        2. approved = [amount <= seen for amount, seen in zip([4, 4], snapshots)]

          Approve both requests independently.

        3. balance = seen - amount

          Each write derives from a stale observation.

        4. print(sum(amount for amount, ok in zip([4, 4], approved) if ok))

          Expose the eight approved units instead of judging safety from balance alone.

        Conventional CPython serialises much Python bytecode execution, while blocking I/O and some native extensions can release the GIL. Optional free-threaded builds and implementation/version differences change assumptions. Measure the actual runtime; do not promise CPU scaling from threads.

        Predict before you run

        How much does the model approve from an opening balance of five?

        Separate bytecode policy from application policyPYTHON 3

        Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

        Preparing the editor controls. Run and editing become available when this page is interactive.

        Browser Python limits

        Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

        Change one thing; explain the difference.

        Start below either request.

        Try: Set balance = 3.

        Both approvals become False and the balance stays three.

        Report the invariant explicitly.

        Try: Add print(sum(amount for amount, ok in zip([4, 4], approved) if ok) <= 5).

        It prints False for the original fixture; the violation becomes visible.

        Before you move on

        Would moving this same unprotected read/check/write design to a free-threaded interpreter fix the overspend?

        Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.

        Read a worked answer

        No. It changes execution opportunities, not the stale decision rule. Use one protected transition or one state owner regardless of the runtime.

        This is a self-check, not a required quiz or a saved score. You can revisit any concept.

        Deadlocks and cancellation

        Deadlock is a cycle of waiting that cannot make progress on its own. Use a consistent order for multiple locks and a cooperative stop policy for running workers; cancelling a handle cannot safely kill arbitrary thread code.

        READ / UNDERSTAND / THEN EXPERIMENT

        Understand first

        Two individually well-protected objects can still deadlock when callers acquire their locks in opposite orders. Learn the wait relationship before reproducing a hang. This bounded planning program is safe in the browser because it never blocks.

        Words you will see

        Deadlock
        A dependency cycle in which participants wait for resources that the cycle itself prevents from being released.
        Lock order
        A common ordering every caller follows when acquiring several locks.
        Cooperative cancellation
        A worker notices a stop request at defined safe points and exits with cleanup.

        Break the cycle before it starts

        The requests name the same two resources in opposite orders. sorted(set(pair)) gives both the order cash, stock and removes a duplicate resource if a request names it twice. This assumes resource names identify unique locks and every path follows the order.

        A non-reentrant lock acquired twice by one thread can block that thread too. Deduplication is a planning choice, not a real lock manager. Production code must map identities to shared lock objects and release acquired locks even when later work fails.

        Stopping is a protocol, not a forced interruption

        The stop flag is already true, so the loop exits before pack. In a real thread lab, use threading.Event for cross-thread signalling, bound blocking operations with suitable timeouts and release resources in finally or context managers.

        Future.cancel can cancel work that has not started; it does not forcibly unwind running thread code. A worker that never checks a stop request or stays in unbounded I/O can outlive the caller's patience. Thread dumps and wait diagrams help diagnosis; sleeping longer is not a deadlock fix.

        The original example, step by step

        These steps explain the original code below. They do not change when you edit your own experiment.

        1. requests = [('stock', 'cash'), ('cash', 'stock')]

          Represent the two contradictory acquisition requests.

        2. plans = [tuple(sorted(set(pair))) for pair in requests]

          Give both requests one common resource order.

        3. if stop_requested:

          Check the modeled stop request before starting a job.

        4. print(completed)

          Display an empty list because neither job started.

        A worker that holds a lock while waiting for another task needing that lock can deadlock. Use timeouts, ownership diagrams and thread dumps during diagnosis. Cancelling a future does not forcibly stop arbitrary running thread code; design cooperative cancellation.

        Conceptual wait cycle and its ordering alternative

        Conceptual reasoning steps for the original example, not a live trace of your edited Python.

        1. CycleA owns left and waits for right; B owns right and waits for left.
        2. OrderBoth request left before right.
        3. ProgressOne waits without holding right, so the owner can finish and release.
        Predict before you run

        Does the true stop flag mean a running OS thread was killed?

        Plan a common lock orderPYTHON 3

        Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

        Preparing the editor controls. Run and editing become available when this page is interactive.

        Browser Python limits

        Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

        Change one thing; explain the difference.

        Allow the modeled jobs.

        Try: Set stop_requested = False.

        completed becomes ['pack', 'send']; this still says nothing about real thread interruption.

        Request one resource twice.

        Try: Add ('cash', 'cash') to requests.

        Its plan is ('cash',), avoiding a repeated acquisition in this ordering policy.

        Before you move on

        If a third path acquires stock before cash, does ordering only the first two paths prevent every cycle?

        Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.

        Read a worked answer

        No. The ordering rule must cover every path that acquires these resources. One contrary path can recreate the cycle.

        This is a self-check, not a required quiz or a saved score. You can revisit any concept.

        Make the explanation your own.

        Use Save work and place to store notes with your code. Unsaved edits stay in this course tab; export before leaving. Reading milestones remain separate.

        Take a versioned study copy

        Export this lesson's original theory, textual model explanations, worked examples, public exercise checks and local-runtime boundaries for reading/review. This is separate from exporting your private workspace: no learner code, notes, identity, saved place or results are included. Offline server/browser execution is not provided.

        Worked examples and explained concept checkpoints remain included. Reference answers for independent work are excluded unless you explicitly select them. A downloaded answer is not an earned pass.

        REFLECT, THEN CONTINUE

        Make this a milestone.

        Save a self-reported core reading milestone and confidence. Confidence 1-3 schedules a review when none is already set; higher confidence does not create a new review. This is not a code execution pass or proof of mastery. Deep-dive reading is optional and is not tracked separately yet.

        Your account

        Loading account...

        Sign in to save your work across devices.