Module contents
Lesson 23 of 26Advanced 110 min

CPU parallelism: threads, processes and speedup laws

The i9-14900HX has 24 heterogeneous cores and most Python code uses one. Study Amdahl's and Gustafson's laws, threads versus processes and the GIL (including free-threaded Python), OpenMP in C++, races and false sharing, and load balancing between P-cores and E-cores, measuring strong and weak scaling on real problems.

After this lesson you can

  • Apply Amdahl's and Gustafson's laws to predict and explain measured speedups.
  • Choose between threads, processes and native code without the GIL according to the workload.
  • Parallelize C++ loops with OpenMP, including reductions and dynamic scheduling.
  • Detect and correct race conditions and false sharing.
  • Parallelize Monte Carlo with independent streams and obtain results reproducible regardless of worker count.

Before you start

Motivation: 24 cores and an interpreter that uses one

The reference i9-14900HX in this curriculum has 24 physical cores and 32 logical processors: 8 performance cores (P-cores) with two hardware threads each and 16 efficiency cores (E-cores) with one. A normal Python loop uses just one. Workloads you will build in this curriculum are full of independent work that could be distributed:

  • AlphaZero self-play. Each training game is independent of the others: 24 processes playing at once generate data 24 times faster if nothing gets in the way (you will see this in the self-play pipeline).
  • Hyperparameter sweeps. A hundred configurations of a small model are a hundred training runs without communication between them.
  • Backtests. Evaluating a thousand strategies, or one strategy over a thousand walk-forward windows, is a textbook “embarrassingly parallel” workload.
  • Monte Carlo. Each sample block of a Monte Carlo estimator is computed without consulting the others.

Yet when you try it, you will see disappointing speedups: 24 threads running 1.0 times as fast as one, 32 slower than 16, or a result changing with thread count. This lesson explains each surprise with a quantitative model and gives you tools to avoid them. It starts with laws predicting expected speedup; continues with what separates threads from processes in Python (the GIL); moves to C++ with OpenMP; studies two classic shared-memory failures (race conditions, which break correctness, and false sharing, which hurts performance); covers heterogeneous cores and load balancing; and ends with parallel Monte Carlo whose result does not depend on worker count. The two labs measure all this on your machine.

The work–span model from the parallel algorithms lesson gives the theoretical limit: with work WW and span DD, no scheduler goes below max⁡(W/p,D)\max(W/p, D). Here the question is more practical: what happens on a particular processor, in a particular language, with memory shared among all.

Speedup, efficiency and Amdahl’s law

Before parallelizing anything, you need to know what is measured.

The difference is not pedantic. A parallel program on one processor is often slower than the sequential one (it creates threads, synchronizes and splits work), so T(1)/T(p)T(1)/T(p) is always more flattering than T⋆/T(p)T^\star/T(p). This is the previous lesson’s fair comparison applied to parallelism: the baseline is the best sequential code, not your parallel version tied to one thread. In this lesson’s labs both coincide because the parallel version with one worker does exactly the same work as the sequential one; when they do not, say so.

Amdahl’s law: strong scaling

In 1967 Gene Amdahl argued at the AFIPS conference that multiprocessors have a ceiling: the part of the program that cannot be distributed. The argument fits on one line, and is worth writing with all its assumptions.

Proof

With pp processors, the sequential part still takes ff and the parallel part (1−f)/p(1 - f)/p, so T(p)=f+(1−f)/pT(p) = f + (1 - f)/p and S(p)=T(1)/T(p)S(p) = T(1)/T(p) is the formula. Since (1−f)/p>0(1 - f)/p > 0 for f<1f < 1, the denominator exceeds ff and S(p)<1/fS(p) < 1/f; if f=1f = 1, S(p)=1=1/fS(p) = 1 = 1/f and the strict bound does not hold, but there is nothing to parallelize either. The limit follows from (1−f)/p→0(1 - f)/p \to 0.

∎

This is the first component of the Amdahl and Gustafson laws. The law measures strong scaling: the problem is fixed and processors are added. Its numbers are stark. With f=5 %f = 5\,\% and 24 cores, S=1/(0.05+0.95/24)≈11.16S = 1/(0.05 + 0.95/24) \approx 11.16: half the cores are lost. Even infinitely many cores would not exceed 20. The derivative at p=1p = 1 is S′(1)=1−fS'(1) = 1 - f, nearly ideal, but the curve bends as (1−f)/p(1 - f)/p approaches ff, that is, around p≈(1−f)/fp \approx (1 - f)/f, which with f=5 %f = 5\,\% is 19 cores.

The assumptions are optimistic in everything except ff: perfect distribution, no synchronization cost and identical processors competing for nothing. In practice each fails, which is why it helps to invert the law.

The Karp–Flatt metric

If you measure S(p)S(p), you can solve for the ff that Amdahl says would explain it:

1S=f+1−fp⟹e(p)=1/S(p)−1/p1−1/p.\frac{1}{S} = f + \frac{1 - f}{p} \quad\Longrightarrow\quad e(p) = \frac{1/S(p) - 1/p}{1 - 1/p}.

Alan Karp and Horace Flatt proposed this experimentally determined sequential fraction as a diagnostic in 1990 (Measuring parallel processor performance, Communications of the ACM 33(5)). Its value lies in how it changes with pp:

  • Constant e(p)e(p): the program behaves as Amdahl predicts, with a genuinely sequential part. To improve, reduce it.
  • Increasing e(p)e(p): a cost grows with pp (synchronization, communication, contention for memory or a lock). Amdahl, which has no such cost, interprets it as an increasing sequential fraction.

The first cell checks this with two explicit T(p)T(p) models: one with only f=2 %f = 2\,\% and another additionally containing a synchronization cost 0.002 p0.002\,p that grows with processor count.

[ ]Amdahl, Gustafson and Karp–Flatt from scratchBrowser
import numpy as np

def amdahl(f, p):
    """Speedup con una fracción f del tiempo secuencial que no se paraleliza."""
    return 1.0 / (f + (1.0 - f) / p)

def gustafson(s, p):
    """Speedup escalado: s es la fracción secuencial de la ejecución PARALELA."""
    return p - s * (p - 1)

def karp_flatt(S, p):
    """Fracción secuencial que explicaría, según Amdahl, el speedup S medido con p procesadores."""
    return (1.0 / S - 1.0 / p) / (1.0 - 1.0 / p)

print(f"Amdahl, f = 5 %:  S(24) = {amdahl(0.05, 24):.4f},  S(1e6) = {amdahl(0.05, 1e6):.4f},  1/f = {1 / 0.05:.0f}")
s = 0.05
f_eq = s / (s + 24 * (1 - s))           # la misma ejecución vista desde un solo procesador
print(f"Gustafson, s = 5 %:  S(24) = {gustafson(s, 24):.2f};  f de Amdahl equivalente = {f_eq:.5f} "
      f"-> amdahl = {amdahl(f_eq, 24):.2f}")

# Karp-Flatt sobre dos modelos explícitos de T(p): solo fracción secuencial, o además un coste de sincronizar c·p
ps = np.array([2, 4, 8, 16, 24, 32])
for nombre, c in (("f = 2 %", 0.0), ("f = 2 % y sincronización 0.002 p", 0.002)):
    T = 0.02 + 0.98 / ps + c * ps        # T(1) = 1 + c
    S = (1.0 + c) / T
    print(f"{nombre:34s} S = {np.round(S, 2)}\n{'':34s} e = {np.round(karp_flatt(S, ps), 4)}")

With only the sequential part, e(p)=0.02e(p) = 0.02 for every pp. With synchronization cost, ee rises from 0.0260.026 to 0.0860.086 and speedup peaks (9.21 with 24), then falls: 32 processors are slower than 24. No constant ff produces that, because Amdahl’s curve increases with pp. When speedup falls, look for a cost growing with pp.

Gustafson’s law: weak scaling

In 1988 John Gustafson published a two-page note in Communications of the ACM, Reevaluating Amdahl’s law, with Sandia results on a 1024-processor hypercube: speedups of 1021 in conjugate-gradient stress analysis, 1020 in finite-difference wave simulation and 1016 in unsteady flow, with sequential fractions of 0.4 to 0.8%. Under Amdahl, f=0.4 %f = 0.4\,\% and p=1024p = 1024 would give S≈201S \approx 201. What is the catch?

Nobody buys 1024 processors to solve the same problem. More hardware solves a larger problem (a finer grid, more steps, more games) in the same time. If in the parallel execution a fraction ss of time is sequential and the rest, 1−s1 - s, is work distributed over pp processors, the same work would take s+p(1−s)s + p(1 - s) on one processor. The ratio is scaled speedup:

SG(p)=s+p(1−s)s+(1−s)=p−s (p−1).S_G(p) = \frac{s + p(1 - s)}{s + (1 - s)} = p - s\,(p - 1).

This is Gustafson’s law (he attributes it to a suggestion by E. Barsis), measuring weak scaling: constant work per processor. With s=5 %s = 5\,\% and 24 processors it gives 22.8522.85; it is a straight line of slope 1−s1 - s, without a ceiling.

The two laws do not contradict each other: they describe the same run with different normalizations. The sequential part accounts for ss of parallel execution time, but in hypothetical one-processor time it accounts for

f=ss+p(1−s),f = \frac{s}{s + p(1 - s)},

which with s=5 %s = 5\,\% and p=24p = 24 is 0.002190.00219. Substituting into Amdahl gives 22.8522.85 again (the previous cell checks it). What changes is the question: Amdahl asks how much faster I solve this problem; Gustafson, how much larger a problem I solve in this time. For self-play or hyperparameter sweeps, Gustafson’s question is usually right; for the latency of a query or backtest needed now, Amdahl’s.

Heterogeneous cores

Both laws assume identical processors. A 14900HX does not have them: the first lab measures that in an AVX2-vectorized dot product, an E-core runs at less than half the speed of the fastest P-core (0.43), and in a scalar loop such as Mandelbrot, about two thirds (0.69). Mark Hill and Michael Marty extended Amdahl to asymmetric processors (Amdahl’s Law in the Multicore Era, IEEE Computer, 2008); the case needed here is simple. With 8 cores of speed 1 and 16 of speed rr, using fast ones first, the capacity of pp threads is

C(p)=min⁡(p,8)+r max⁡(0,p−8).C(p) = \min(p, 8) + r\,\max(0, p - 8).

If parallel work is distributed in proportion to speed (dynamic scheduling: each core takes work when it finishes its current task), it takes (1−f)/C(p)(1 - f)/C(p) and S=1/(f+(1−f)/C(p))S = 1/(f + (1 - f)/C(p)). If distributed equally (static scheduling), each thread receives (1−f)/p(1 - f)/p and a slow one finishes last: the parallel part takes (1−f)/(p r)(1 - f)/(p\,r) as soon as p>8p > 8. With r<8/9r < 8/9, moving from 8 to 9 threads worsens time, and with 24 threads static scheduling performs like 24 slow cores.

InteractiveAmdahl, Gustafson and your measurements
048121620242832148121620242832cores pS1/f = 20.0
  • ideal S = p
  • Amdahl with f
  • Monte Carlo with threads
  • Amdahl with fitted f
The Monte Carlo with threads points are explained by a sequential fraction of 20.1 %. No one writes a program with that much sequential work: what Amdahl attributes to f here is the GIL, shared bandwidth, slow cores and synchronization costs.
Model
5.0 %
Measured points
S(24) with this f11.16
Efficiency with 2447 %
Limit 1/f with infinitely many cores20.0
f that best fits the points20.1 %
Karp-Flatt with p = 3225.9 %
In Amdahl mode, the orange curve is S(p)S(p) with the slider's ff and blue points are speedups measured in the labs' reference run: Monte Carlo with Python threads, threaded stencil and OpenMP Mandelbrot; you can also enter yours. The dashed magenta curve is the ff that best explains them, and the Karp–Flatt reading uses the last point. Start with f=5 %f = 5\,\%: Monte Carlo points are far below. What ff would be needed? In Gustafson mode compare the scaled line with Amdahl for the same number. In heterogeneous mode lower speed rr of the 16 slow cores and see what happens to static scheduling across p=8p = 8.

The figure’s points come from the first lab, and the ff fitted to Monte Carlo and the Python-threaded stencil is huge: 20% and 33%. Neither program has that much written sequential work: almost all is distributed into independent blocks. What Amdahl attributes to ff is the rest of the lesson: the GIL, shared bandwidth, slow cores and synchronization cost. And something Amdahl cannot explain with any ff: both speedups peak and then fall (Monte Carlo, from 4.34 with 12 threads to 3.54 with 32). The Karp–Flatt metric, increasing with pp, hints at costs growing with processor count. OpenMP Mandelbrot, by contrast, without the GIL and with dynamic scheduling, fits an ff below 1%.

Threads and processes

A process is a running program with its own address space: its memory, open files and interpreter copy. A thread is an execution stream inside a process: threads in one process share all memory and each has only its own stack and registers. That difference determines communication cost.

ThreadsProcesses
Memoryshared: everyone sees an array without copyingisolated: data is copied (serialized with pickle) or put in explicit shared memory
Creationmicrosecondstens to hundreds of milliseconds with spawn: starts another interpreter and imports modules
A failurecan bring down the whole processisolated to its process
Typical hazardrace conditionsserialization and startup cost

This is grouped under threads, processes and the GIL, and in C++ the choice is almost always threads. In Python a third factor changes everything.

El GIL

CPython protects its internal state (each object’s reference counts, memory allocator, module dictionaries) with one global lock, the GIL (global interpreter lock). A thread can execute Python bytecode only while holding the GIL. If another requests it, the holder releases it after a switch interval (sys.getswitchinterval(), 5 ms by default) or when blocking. As a result, two threads executing pure Python never run simultaneously, even with 32 logical processors. They take turns.

The GIL does not prohibit parallelism, only parallelism inside the interpreter. C code that does not touch Python objects can release it while working, and much important code does:

  • NumPy releases the GIL in inner loops of ufuncs and reductions on numeric types, and during BLAS calls. Its multithreaded random-generation documentation shows independent Generator filling arrays from different threads.
  • I/O: reading a file, waiting for a socket or HTTP request releases the GIL while waiting. Python threads therefore do help I/O-bound workloads.
  • Compiled extensions: ctypes releases the GIL during a call to a library function loaded with CDLL; Numba releases it in @njit(nogil=True) functions, and prange loops distribute work among native threads that do not need it; pybind11 releases it with py::gil_scoped_release (seen in Python–C++ bindings).

Practical rule: threads speed up Python to the extent time is spent outside the interpreter. If each work chunk spends a fraction gg of time with the GIL and 1−g1 - g without it, at most one thread at a time is in the GIL-held part, and speedup cannot exceed 1/g1/g, Amdahl with f=gf = g. That is why chunk size matters in NumPy: with 4096-element arrays each ufunc takes little more than its fixed call cost (paid with the GIL), whereas with 65 536-element arrays fixed cost is diluted. The first lab measures this.

Free-threaded Python (PEP 703)

In 2023 Sam Gross proposed a GIL-free CPython build in PEP 703 (--disable-gil), based on biased reference counting, immortal objects, deferred reference counting and the thread-safe mimalloc allocator. In his prototype, single-thread overhead was 6% on Intel Skylake and 5% on AMD Zen 3 on the pyperformance benchmark. Python 3.13 included it as an experimental build offered by official Windows and macOS installers (the executable carries an t: python3.13t). PEP 779 set criteria for support and declared it supported in Python 3.14, though not yet by default; current documentation estimates single-thread overhead between 1% on macOS ARM and 8% on Linux x86-64.

Two practical details. sys._is_gil_enabled() says whether the GIL is active in the process, because importing a C extension that does not declare free-threaded compatibility re-enables it (with a warning). Removing the GIL does not remove races: without it, two threads performing x += 1 on the same Python variable can lose updates, as in C++ (CPython guarantees internal objects do not become corrupted, not that your read-modify-write is atomic). In today’s scientific environment, the robust choice remains threads for NumPy, I/O and compiled code that releases the GIL; processes for pure Python.

Python tools

concurrent.futures provides the same interface for threads and processes, and is a good starting point:

from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor

with ThreadPoolExecutor(max_workers=8) as ex:          # hilos: NumPy, E/S, código que suelta el GIL
    resultados = list(ex.map(tarea, argumentos))       # map devuelve en el orden de los argumentos

with ProcessPoolExecutor(max_workers=8) as ex:         # procesos: Python puro
    futuros = [ex.submit(tarea, a) for a in argumentos]
    resultados = [f.result() for f in futuros]         # result() relanza la excepción del worker

map returns results in input order even if they finish in another order; as_completed yields them as they finish. For processes, map(..., chunksize=k) sends kk tasks in kk and reduces communication cost when there are many small ones.

multiprocessing and the start method

An ProcessPoolExecutor creates processes using one of three multiprocessing methods. fork duplicates the parent process (fast, but also copies locks held by other threads and can leave the child blocked); spawn starts a new interpreter that imports the main module then unpacks the function and arguments; forkserver requests children from a clean server forked at the start. spawn is the default on Windows and macOS (on macOS since Python 3.8); since Python 3.14, the default on Linux and other supporting POSIX platforms is forkserver, and fork is no longer the default anywhere.

With spawn there are two rules; breaking them causes the most bewildering multiprocessing errors:

  1. The main module is reimported in each child. If process-creation code is at module level, each child executes it again on import and tries to create its own children. Python detects this: each child fails with an RuntimeError mentioning the process “bootstrapping phase” and the pool breaks (BrokenProcessPool); in older versions or launchers masking it, the symptom is an avalanche of processes. The solution is the guard:

    def main():
        with ProcessPoolExecutor() as ex:
            print(sum(ex.map(trabajo, range(100))))
    
    if __name__ == "__main__":       # en el hijo, __name__ es "__mp_main__": no se ejecuta
        main()
  2. Functions travel by name. pickle sends the function’s module and name, not its code, and the child imports it. A function defined in an interactive interpreter or Jupyter cell lives in an __main__ the child cannot import: the documentation warns such examples do not work interactively and fail with AttributeError: Can't get attribute 'f' on <module '__main__'>. Put worker functions in an importable .py file. The lab does this by writing a small module.

joblib and shared memory

joblib.Parallel(n_jobs=8)(delayed(f)(x) for x in xs) is the interface used by scikit-learn. Its default backend, loky, reuses processes across calls (startup is paid once) and passes large NumPy arrays to workers through memory-mapped files instead of copying them through a pipe. If your data is a large read-only array, that is exactly what you want.

When you need to share an array explicitly between processes, multiprocessing.shared_memory.SharedMemory creates a named block each process wraps with np.ndarray(forma, dtype, buffer=shm.buf) without copying. It works, but brings all thread problems back to processes: two writing the same region cause a race.

OpenMP in C++

For the hot loop already compiled and optimized in C++, the most direct way to use all cores is OpenMP, a shared-memory directive standard supported by GCC, Clang and MSVC. The program starts with one thread; on reaching an parallel region, it creates a team of threads (or reuses one), all execute the region and wait at an implicit barrier at the end. This is the fork–join work–span model written with annotations:

#include <omp.h>

double suma_cuadrados(const double* x, std::int64_t n) {
    double s = 0.0;
    #pragma omp parallel for reduction(+:s) schedule(static)
    for (std::int64_t i = 0; i < n; ++i)
        s += x[i] * x[i];
    return s;
}

Compile with -fopenmp (GCC, Clang) or /openmp (MSVC) and that is it. The elements you will use, collectively called OpenMP and shared memory:

  • parallel for: distributes loop iterations among team threads. The loop must have canonical form (an integer index, a limit unchanged inside) and independent iterations: OpenMP does not check this.
  • Shared and private variables. Variables declared outside the region are shared by default; those declared inside, and the loop index, are private to each thread. private(t) gives each thread an uninitialized copy; firstprivate(t) gives one initialized to the previous value; default(none) requires each variable’s status to be declared and turns an omission into a compile error, recommended for serious code.
  • reduction(+:s): each thread accumulates in a private s copy initialized to the operation’s identity, and at the end copies are combined with the original. Without this clause, s += ... from all threads would race. This is the algorithm lesson’s parallel reduction, with the combination tree hidden.
  • schedule: how iterations are distributed. static divides them into nearly equal contiguous blocks, one per thread, decided in advance. static, c creates cc-iteration blocks and assigns them round robin. dynamic, c queues blocks of cc for each thread to take on finishing (c=1c = 1 by default). guided, c does the same with blocks starting large and shrinking in proportion to remaining iterations divided by thread count, no smaller than cc. You will study this below.
  • num_threads(h), omp_set_num_threads or environment variable OMP_NUM_THREADS set team size; omp_get_thread_num() gives the thread index and omp_get_wtime() a wall clock.

MSVC implements version 2.0 of the standard, from 2002, with /openmp, enough for this lesson; GCC and Clang support much newer versions (tasks, simd, GPU offloading). From Python, the simplest way to call that code is to compile it as a shared library and load it with ctypes, which releases the GIL during the call: that is what the second lab does.

Correctness: race conditions

With shared memory, the gravest failure is an incorrect result rather than slowness.

The canonical example is a shared counter. x = x + 1 is not one operation but three: read x from memory into a register, add 1 in the register, and write it to x. If two threads read the same value before either writes, both write the same result and one increment is lost. In C++ it is worse: the standard says a program with a data race has undefined behavior, so the compiler may, for example, keep x in a register throughout the loop and write it only once at the end.

InteractiveReplay a race condition
Thread A
register r = 2
  1. r ← x
  2. r ← r + 1
  3. x ← r
  4. r ← x
  5. r ← r + 1
  6. x ← r
Shared memory
x = 3
12 of 12 operations
Thread B
register r = 3
  1. r ← x
  2. r ← r + 1
  3. x ← r
  4. r ← x
  5. r ← r + 1
  6. x ← r
A: r ← x (r=0)B: r ← x (r=0)A: r ← r + 1B: r ← r + 1A: x ← r → x=1B: x ← r → x=1A: r ← x (r=1)A: r ← r + 1A: x ← r → x=2B: r ← x (r=2)B: r ← r + 1B: x ← r → x=3
Result over 2000 random interleavings01211713761468x =
  • thread A
  • thread B
  • correct result
  • lost updates
  • your interleaving
1 of 4 increments were lost: a thread wrote a value read before the other wrote its own.
Increment
Increments per thread K
x in memory3
Correct value 2K4
Lost increments1
Minimum seen in 2000 random runs2
Two threads each make KK increments of a shared counter. Choose the interleaving with «Paso de A» or «Paso de B»; the trace below shows what executed. Start with the classic interleaving: both read 0, both write 1 and one increment is lost. Load «El peor caso» and explain how it ends at x=2x = 2 with K=4K = 4, when it should be 8. Then switch to «Atómico» and «Reducción por hilo» and look for an interleaving that loses something. The histogram counts results of 2000 random interleavings.

How much can be lost? Almost everything.

Proof

Every write writes a read value plus 1, and x never drops below 0, so every write is at least 1. Let B be the thread making the program’s last write; it writes (what it read on its last read) + 1. Since K≥2K \ge 2, B’s last read follows its penultimate write, so at that instant x has been written at least once and is at least 1: B writes at least 2, the final value. To construct it: A reads 0 and adds (register 1), without writing. B performs K−1K - 1 complete increments. A writes 1. B reads 1 and adds (register 2), without writing. A performs its remaining K−1K - 1 increments. B writes 2.

∎

This is the figure’s «El peor caso» button. The next cell counts, for each KK, how many of the (6K3K)\binom{6K}{3K} possible interleavings leave each value, using dynamic programming over state (program counters, registers and xx) instead of enumerating them; it confirms the minimum and that every value between 2 and 2K2K is reachable.

[ ]All results of a raceBrowser
from functools import lru_cache
from math import comb

def distribucion(K):
    """Para dos hilos con K incrementos no atómicos cada uno (leer, sumar, escribir), cuenta cuántos de los
    C(6K, 3K) entrelazados dejan cada valor final de x. Programación dinámica sobre el estado de la máquina."""
    n = 3 * K
    @lru_cache(maxsize=None)
    def contar(a, b, ra, rb, x):
        if a == n and b == n:
            return {x: 1}
        total = {}
        for hilo in (0, 1):
            pc, r = (a, ra) if hilo == 0 else (b, rb)
            if pc == n:
                continue
            x2 = x
            if pc % 3 == 0:
                r = x            # leer
            elif pc % 3 == 1:
                r = r + 1        # sumar en el registro
            else:
                x2 = r           # escribir
            sig = (pc + 1, b, r, rb, x2) if hilo == 0 else (a, pc + 1, ra, r, x2)
            for v, c in contar(*sig).items():
                total[v] = total.get(v, 0) + c
        return total
    return dict(sorted(contar(0, 0, 0, 0, 0).items()))

for K in range(1, 6):
    d = distribucion(K)
    tot = sum(d.values())
    assert tot == comb(6 * K, 3 * K)
    todos = list(d) == list(range(min(d), max(d) + 1))     # ¿aparece cada valor intermedio?
    print(f"K = {K}: {tot:>11,d} entrelazados; valores {min(d)}..{max(d)} (todos: {todos}); "
          f"correctos (x = {2 * K}): {d[2 * K] / tot:7.3%}; con x = 2: {d.get(2, 0):,d}")

With K=2K = 2, only 6 of 924 interleavings (those overlapping no pair of increments) give the correct value, and 702 give the minimum, 2. With K=5K = 5 there are over 155 million interleavings and the correct fraction is negligible. Counting interleavings uniformly is not a physical probability (hardware does not choose randomly), but the message is robust: without synchronization, the correct result is the exception. The OpenMP lab confirms it on real hardware: with 2 threads and ten million increments, the counter reaches 60%.

Three ways to fix it

  • Atomic operations. #pragma omp atomic before c += 1, or std::atomic<long long> with fetch_add, make the increment one indivisible operation (on x86, an instruction with lock prefix). It is correct, but each increment requires the core to hold c’s cache line exclusively, and with multiple threads that line travels between cores: the lab measures the atomic loop slower with 2 threads than 1.
  • Locks. #pragma omp critical, std::mutex or threading.Lock in Python protect an entire section: only one thread executes it at a time. They help update complex structures (a dictionary, a list), but serialize: the critical section is literally Amdahl’s ff.
  • Per-thread reduction. Each thread accumulates in its private variable and finally the pp variables are combined, with one atomic operation or lock per thread, not per increment. This is what reduction(+:c) does, and is the default choice whenever the problem permits.

Tools for finding races you cannot see are dynamic detectors: ThreadSanitizer (-fsanitize=thread in GCC and Clang) instruments each access and warns about conflicting unsynchronized access pairs. Its cost is high (the program runs several times slower), so it is used in tests rather than production. The Art of Multiprocessor Programming (Herlihy, Shavit, Luchangco and Spear) is the reference for the underlying locks, atomics, lock-free structures and memory models.

Floating-point reductions: order matters

A correct parallel reduction has another surprising effect: the result changes with thread count. Floating-point addition is not associative (as seen with pairwise summation), and reduction(+:s) with pp threads sums pp segments separately then combines partials: different order, different rounding. The OpenMP standard explicitly leaves reduction combination order unspecified, so even two runs with the same threads need not match bit for bit (with schedule(static) and the same thread count, they often do in practice).

If reproducibility is needed (debugging, comparing versions or auditing a result), separate work decomposition from thread count: fixed-size blocks, each summed in order, with partials always combined in the same order. Thread count decides who sums each block, not what is added to what.

[ ]Summation order and fixed blocksBrowser
import math
import numpy as np

rng = np.random.default_rng(23)
x = rng.normal(size=1 << 20) * np.logspace(0, 8, 1 << 20)    # sumandos de magnitudes muy distintas
exacta = math.fsum(x)

def secuencial(v):
    return float(np.cumsum(v)[-1])          # cumsum suma de izquierda a derecha, como un bucle for

def reduccion_openmp(x, p):
    """Como reduction(+:s) con schedule(static): un tramo contiguo por hilo y luego se combinan los parciales."""
    parciales = [secuencial(t) for t in np.array_split(x, p)]
    return secuencial(np.array(parciales))

def bloques_fijos(x, B=4096):
    """Bloques de tamaño fijo, independientes del número de hilos, combinados siempre en el mismo orden."""
    parciales = [secuencial(x[i:i + B]) for i in range(0, len(x), B)]
    return secuencial(np.array(parciales))

print(f"exacta (fsum)        {exacta!r}")
for p in (1, 2, 3, 4, 8, 24):
    r = reduccion_openmp(x, p)
    print(f"reduction, p = {p:2d}   {r!r}   error relativo {abs(r - exacta) / abs(exacta):.1e}")
b = bloques_fijos(x)
print(f"bloques fijos        {b!r}   error relativo {abs(b - exacta) / abs(exacta):.1e}  (no depende de p)")

All six reduction results differ and have relative errors of order 10−1410^{-14}: none is “the correct one”. The blocked version does not depend on pp because pp does not appear in it, and is also more accurate (relative error 2.8×10−152.8 \times 10^{-15}), because block summation is a step toward pairwise summation. The OpenMP lab does the same in C++ with real threads.

Performance: false sharing, bandwidth and oversubscription

A correct parallel program can still be slow for reasons in the hardware shared by cores rather than in the code.

False sharing

Caches do not store individual bytes but 64-byte lines (locality in lesson 19). When several cores have copies of the same line, a coherence protocol (MESI and variants) ensures all see the same value: to write, a core needs the line in Modified state, requiring all other copies to be invalidated. If another core then writes that line, it must request it: the line travels from cache to cache and the first copy becomes invalid.

Now imagine four threads, each incrementing its own counter, with counters in an long long c[4] array. They share no data and there is no race. But the four counters occupy 32 consecutive bytes in the same line, and each thread’s write invalidates the other three copies. That is false sharing: sharing a line without sharing data.

InteractiveFalse sharing in cache lines
core 0c0=6L1Icore 1c1=6L1Icore 2c2=6L1Icore 3c3=6L1Mmemory: one 64 B line with the counters
Write 24: core 3 requests the line, modified in core 2; it moves between caches and core 2’s copy is invalidated.
write 24 / 24
  • M: modified, unique copy
  • I: invalidated copy
  • transfer between caches
Measured in the lab: time with counters packed / separated by 64 B
  • ordinary increment
  • atomic increment
2 threads
1.1×
3.3×
4 threads
1.3×
7.1×
8 threads
1.3×
9.4×
16 threads
1.8×
11.7×
The threads share no data, but they do share a cache line: 23 of 24 writes force it to move between caches. With atomic increments each write requires exclusive ownership, as in the animation with bursts of 1; with ordinary increments the write buffer groups several per trip, like longer bursts, reducing the measured effect.
Counter layout
Threads
Consecutive writes per thread b
Writes24
Memory loads1
Transfers between caches23
Transfers per write (24 writes)0.96
Four cores, each with its L1, take turns writing their counters. «Juntos»: counters are consecutive 8 B values in one 64 B line, and almost every write fetches the line from the cache of the core that modified it (red arrow), invalidating its copy. «Con relleno»: each counter has its own line; after the first load there is no traffic. Lengthen bursts bb (consecutive writes by each thread) and watch transfers per write decrease. Below is the slowdown measured in the lab: with atomic increments each write needs the line (bursts of 1); with normal increments the write buffer groups several per trip (long bursts), greatly reducing the effect.

The solution is to separate data written by different threads: padding to the line size (struct alignas(64) Contador { long long v; };), or better, thread-local variables combined at the end, again a reduction. C++17 defines std::hardware_destructive_interference_size for the minimum separation; on recent Intel CPUs 128 bytes is often recommended because the prefetcher brings lines in pairs, although 64 B separation suffices in the lab. False sharing appears unexpectedly in arrays of per-thread results (resultado[hilo] += ... inside the loop) and small structures with one field per thread.

Bandwidth is shared

The roofline model says a low-arithmetic-intensity kernel is memory-bandwidth-bound. What it did not say is that bandwidth belongs to the chip, not each core: in lesson 19 the whole chip moved about 54 GB/s of physical DRAM traffic. A memory-bound kernel such as a stencil or matrix–vector product cannot speed up with pp threads beyond (chip bandwidth) / (one-thread bandwidth), however many cores you add. Beyond that point extra threads only compete for the same memory. In the lab, the Numba-compiled stencil moves 23.4 GB/s with one thread and at most 58.6 GB/s with all: maximum speedup 2.51, set by memory rather than code.

BLAS oversubscription

NumPy calls a BLAS library (OpenBLAS in PyPI wheels, MKL in other distributions; the lesson 20 BLAS stack) that is already multithreaded: a large A @ A uses all cores. If you also launch 24 processes and each performs matrix products, each process creates its own team of 24 BLAS threads: 576 threads for 32 logical processors. This is oversubscription: the OS shares time among threads competing for the same caches, team threads wait at barriers for teammates not running, and everything is slower than with one BLAS thread per process. The rule is that (workers) × (threads per worker) should not exceed core count. Control it with threadpoolctl:

from threadpoolctl import threadpool_limits

with threadpool_limits(limits=1, user_api="blas"):     # BLAS secuencial dentro de este bloque
    resultados = list(pool.map(tarea, datos))

or with variables OMP_NUM_THREADS, OPENBLAS_NUM_THREADS and MKL_NUM_THREADS, which must be set before importing NumPy. For processes, set the limit inside each worker (in the task itself or the pool’s initializer). joblib with loky automatically limits each worker’s BLAS threads so the product does not oversubscribe the machine.

Heterogeneous cores and load balancing

Static scheduling is cheapest (no shared queue or communication), but works well only if all iterations cost the same and all cores are equally fast. Neither is generally true, and load balancing and scheduling concerns how to distribute work when they fail.

Irregular tasks. The textbook example is the Mandelbrot set drawn by rows: a row crossing the set’s interior exhausts 2000 iterations at every pixel, while one at the image edge escapes in two or three. In the lab’s 1024 × 1024 image, the cheapest row performs 2215 iterations and the most expensive over 1.6 million: a factor over 700. With schedule(static), each thread receives a contiguous row block, and those receiving the set’s center work much more.

Unequal cores. Even if every task cost the same, an E-core takes longer than a P-core for each one. The operating system decides which core runs each thread (on Intel since Alder Lake, with hardware Thread Director hints), and may move them during execution. With static scheduling, the last thread to finish sets the time.

The three OpenMP schedules respond differently:

BlocksDistributionCostWorks well with
static⌈n/p⌉\lceil n/p \rceil contiguous, or cc round robinbefore startingnoneuniform tasks on equal cores
dynamic, cccshared queue: first to finish takes nextone per block (an atomic operation on queue index)irregular tasks, unequal cores
guided, cstart at ≈n/p\approx n/p and shrink to ccshared queuefewer blocks than dynamicirregular tasks without a very expensive end

Block size is a tradeoff: small blocks balance better, but each pays request cost and loses locality; large blocks amortize cost but can leave a slow core with the last expensive block while others wait. guided has a weakness Mandelbrot illustrates: its first blocks are enormous, and if they land in the set’s expensive region or on an E-core, the rest cannot compensate.

InteractiveScheduling on heterogeneous cores
cost per row (iterations), from 0 to 127schedule over time (thousands of P-core iterations)P0P4E0E4E8E12061121182243
  • P-core working
  • E-core working
  • ideal: work / capacity
  • last core finishes
With static scheduling, each thread gets 5 or 6 consecutive rows. The expensive central rows fall to a few threads, some of them slow; the others finish early and wait.
Schedule
Chunk size c (rows)
Machine
0.69
0.05
Total time / ideal3.00×
Speedup versus one P-core6.34
Core idle time64 %
Chunks assigned24
With static: total / ideal3.00×
The 128 rows of a 128 × 128 Mandelbrot (same region as the lab, at most 400 iterations) distributed over 8 P-cores of speed 1 and 16 E-cores of speed rr, defaulting to the lab's measured mean E-core scalar speed. Above, each row's cost; below, what each core does over time (darker means more expensive rows). The dashed line is ideal total work divided by total capacity, and magenta marks the last core's finish. Start with static and see which cores are idle. Try dynamic with blocks of 1 and 16, guided, and raise the cost of requesting each block.

The next cell is the same simulator in Python: it calculates the cost of 128 rows and simulates static, dynamic and guided with distribution cost of 0.05 average rows per block. This is the model plotted in the figure.

[ ]A scheduling simulatorBrowser
import numpy as np

def coste_filas(filas=128, cols=128, maxit=400):
    """Iteraciones de cada fila del Mandelbrot en [-2.1, 0.7] x [-1.25, 1.25] (la región del laboratorio)."""
    ci = -1.25 + 2.5 * np.arange(filas) / filas
    cr = -2.1 + 2.8 * np.arange(cols) / cols
    CR, CI = np.broadcast_to(cr[None, :], (filas, cols)), np.broadcast_to(ci[:, None], (filas, cols))
    zr, zi = np.zeros((filas, cols)), np.zeros((filas, cols))
    it = np.zeros((filas, cols), dtype=np.int64)
    for _ in range(maxit):
        vivo = zr * zr + zi * zi < 4.0                     # el mismo test que el bucle while del C++
        t = zr * zr - zi * zi + CR
        zi = np.where(vivo, 2.0 * zr * zi + CI, zi)
        zr = np.where(vivo, t, zr)
        it += vivo
    return it.sum(axis=1)

def simula(costes, velocidades, plan, c=1, sobrecoste=0.0):
    """Reparto estilo OpenMP; devuelve el instante en que termina el último hilo."""
    n, p = len(costes), len(velocidades)
    libre = np.zeros(p)
    if plan == "static":                                   # bloques contiguos casi iguales, uno por hilo
        for t, idx in enumerate(np.array_split(np.arange(n), p)):
            libre[t] += costes[idx].sum() / velocidades[t]
        return libre.max()
    i = 0
    while i < n:
        tam = max(c, -(-(n - i) // p)) if plan == "guided" else c
        t = int(np.argmin(libre))                          # el primer hilo que queda libre
        libre[t] += costes[i:i + tam].sum() / velocidades[t] + sobrecoste
        i += tam
    return libre.max()

costes = coste_filas()
vel = np.array([1.0] * 8 + [0.69] * 16)                     # 8 P-cores y 16 E-cores de velocidad 0.69
ideal = costes.sum() / vel.sum()
media = costes.mean()
print(f"filas: {len(costes)}, coste mín {costes.min()}, máx {costes.max()}, total {costes.sum():,d}")
for plan, c in (("static", 1), ("dynamic", 1), ("dynamic", 4), ("dynamic", 16), ("guided", 1), ("guided", 4)):
    t = simula(costes, vel, plan, c, 0.05 * media)
    print(f"{plan:8s} c = {c:2d}: tiempo / ideal = {t / ideal:.2f}, speedup frente a un P-core = {costes.sum() / t:.2f}")
print(f"24 núcleos iguales, static: tiempo / ideal = {simula(costes, np.ones(24), 'static') / (costes.sum() / 24):.2f}")

With lab-measured E-core speed (0.69 in scalar code), static takes 3.00 times ideal and dynamic with blocks of 1 takes 1.15. Blocks of 16 are disastrous (5.66 times ideal) for an arithmetic reason: 128 rows in blocks of 16 are 8 blocks for 24 cores, leaving 16 idle. guided falls between (1.94 with c=1c = 1): its first 24 blocks, 6 to 2 rows, are allocated at once covering rows 0 to 87, so the expensive center is in blocks of 3 or 4 rows, and the one landing on an E-core sets the finish. The last line separates causes: even with 24 equal cores, static takes 2.61 times ideal; irregular rows explain most of the problem and heterogeneity the rest.

Affinity. You can pin a process or thread to cores: psutil.Process().cpu_affinity([...]) (Windows and Linux), os.sched_setaffinity (Linux) or, in OpenMP 4.0 and later, OMP_PROC_BIND and OMP_PLACES. Pinning threads prevents OS migration and preserves caches, and lets you measure each core type separately, as the first lab does. But on a heterogeneous processor manual pinning is fragile: dynamic scheduling adapts automatically to each core’s speed, other programs’ load and current frequency.

Parallel and reproducible Monte Carlo

Monte Carlo is a perfect parallel workload: each sample is independent. But two things must be distributed, work and randomness, and the latter is often done incorrectly.

Do not share a generator between threads (NumPy’s Generator have an internal lock, so it is correct but serializes, and the order in which threads obtain numbers depends on scheduling), or seed each worker with semilla + id_worker (streams may overlap and results depend on worker count). The solution follows generators and streams and counter-based generators:

  1. Divide nn samples into BB fixed-size blocks, with BB independent of worker count.
  2. Give each block its own stream with np.random.SeedSequence(semilla).spawn(B): child kk derives from seed entropy and its index kk using a mixing function designed so child streams do not overlap or correlate in practice.
  3. Distribute blocks among workers however you wish and combine results in block order.

Thus worker count decides who computes each block, but not what numbers each sees or their summation order: the result is bit-for-bit identical with 1, 4 or 32 workers. It is the same idea as fixed-block summation above. The cell checks it without threads (Pyodide cannot create threads): it groups blocks into “workers” in different ways and compares with the mistake of per-worker seeding.

[ ]Streams per block, not per workerBrowser
import numpy as np

def bloque(semilla, m):
    """Suma de 4·sqrt(1 − U²) sobre m uniformes del flujo de este bloque (su media es π)."""
    u = np.random.default_rng(semilla).random(m)
    return float(np.sum(4.0 * np.sqrt(1.0 - u * u)))

def por_bloques(n_bloques, m, workers, semilla=2026):
    hijos = np.random.SeedSequence(semilla).spawn(n_bloques)
    # cada worker calcula los bloques k ≡ w (mod workers); el orden de cálculo no importa...
    sumas = [None] * n_bloques
    for w in range(workers):
        for k in range(w, n_bloques, workers):
            sumas[k] = bloque(hijos[k], m)
    return sum(sumas) / (n_bloques * m)     # ...porque se combinan siempre en el orden de los bloques

def por_worker(n, workers, semilla=2026):
    hijos = np.random.SeedSequence(semilla).spawn(workers)          # el reparto depende de workers
    return sum(bloque(h, n // workers) for h in hijos) / n

for w in (1, 4, 16, 64):
    print(f"workers = {w:2d}:  por bloques {por_bloques(64, 4096, w)!r}   por worker {por_worker(64 * 4096, w)!r}")

With per-block streams all four results are the same floating-point number; with per-worker streams they differ from the third decimal place, the scale of Monte Carlo error with 2.6×1052.6 \times 10^5 samples (typical error about 1.7×10−31.7 \times 10^{-3}). With 64 workers they coincide for a trivial reason: each worker is exactly one block with the same child seed. Both are equally good estimators; only one is reproducible. In the lab you will do this with real threads, and the coding exercise asks you to write the general function.

Lab 1: strong and weak scaling in Python

This lab runs on your machine (runtime=local): it needs multiple cores, real threads and processes, Numba for compiled kernels and psutil for affinity. Figures quoted are from the reference run on the i9-14900HX with Windows 11, with the machine shared with other processes: absolute times varied considerably between runs (single-thread time by up to a factor of 2 depending on turbo frequency), so focus on trends and ratios, not milliseconds. Repeat on your machine with everything else closed.

Your processor: fast and slow cores

The first cell pins the process to each logical processor in turn (cpu_affinity) and measures two Numba-compiled kernels: a dot product fitting in L1 and vectorized by the compiler with AVX2, and a scalar Mandelbrot loop. The minimum of three interleaved rounds filters interference from other processes.

[ ]Topology: each core's speedLocal GPU
import os, sys, time, platform
import numpy as np
import psutil
from numba import njit

@njit(fastmath=True)
def simd(a, b, rep):
    """Producto escalar sobre un array que cabe en L1: el compilador lo vectoriza con AVX2."""
    s = 0.0
    for r in range(rep):
        for i in range(a.size):
            s += a[i] * b[i]
    return s

@njit
def escalar(rep):
    """Iteraciones de Mandelbrot: código escalar, con saltos y dependencias."""
    tot = 0
    for r in range(rep):
        for j in range(64):
            cr, ci = -2.0 + 2.5 * j / 64, 0.3
            zr = zi = 0.0
            k = 0
            while k < 200 and zr * zr + zi * zi < 4.0:
                zr, zi = zr * zr - zi * zi + cr, 2 * zr * zi + ci
                k += 1
            tot += k
    return tot

a = np.random.default_rng(0).random(1024)
simd(a, a, 1); escalar(1)                        # compila antes de medir
L = os.cpu_count()
print(f"{platform.processor()}: {psutil.cpu_count(logical=False)} núcleos físicos, {L} procesadores lógicos")

yo = psutil.Process()
original = yo.cpu_affinity()
t_simd, t_esc = np.full(L, np.inf), np.full(L, np.inf)
try:
    for ronda in range(3):                       # rondas intercaladas; el mínimo filtra la carga de otros procesos
        for k in range(L):
            yo.cpu_affinity([k])                 # el proceso solo puede correr en el procesador lógico k
            t0 = time.perf_counter(); simd(a, a, 60_000); t_simd[k] = min(t_simd[k], time.perf_counter() - t0)
            t0 = time.perf_counter(); escalar(600); t_esc[k] = min(t_esc[k], time.perf_counter() - t0)
finally:
    yo.cpu_affinity(original)

v_simd, v_esc = t_simd.min() / t_simd, t_esc.min() / t_esc
orden = np.sort(v_simd)                          # dos grupos: se corta por el mayor salto de velocidad
g = int(np.argmax(np.diff(orden)))
rapido = v_simd > (orden[g] + orden[g + 1]) / 2
print("velocidad relativa al lógico más rápido (SIMD | escalar):")
for k in range(0, L, 8):
    print("  ".join(f"{j:2d}: {v_simd[j]:.2f}|{v_esc[j]:.2f}" for j in range(k, min(k + 8, L))))
print(f"grupo rápido: {rapido.sum()} lógicos; grupo lento: {(~rapido).sum()} lógicos")
if (~rapido).any():
    print(f"velocidad media del grupo lento: SIMD {v_simd[~rapido].mean():.2f}, escalar {v_esc[~rapido].mean():.2f}")
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

In the reference run, splitting at the largest jump separates two groups of 16 logical processors. Logical 0 to 15 are the 8 P-cores with two hardware threads each: they range from 0.79 to 1.00 in the vectorized kernel (variation comes from other processes and current frequency, which varies by core). Logical 16 to 31 are E-cores: 0.43 on average in the vectorized kernel and 0.69 in scalar code. Two conclusions. First, an E-core’s relative speed depends on the code: there is no single rr, and modeling your workload requires measuring it with your kernel. Second, the specification’s “24 cores” is worth roughly 8+16⋅0.43≈14.98 + 16 \cdot 0.43 \approx 14.9 P-cores for vectorized code and 8+16⋅0.69≈19.08 + 16 \cdot 0.69 \approx 19.0 for scalar code: the heterogeneous model’s C(24)C(24) capacities. Treat them as estimates: each core is measured alone here at single-core turbo frequency, while with all busy the chip shares its power limit and frequencies change. A P-core’s hardware threads share execution units, so do not count as whole cores.

The GIL in action

The second cell writes a small module with worker functions (with spawn they must be importable, as seen) and distributes fixed work into pp equal tasks: integer arithmetic in pure Python, the same work in NumPy ufuncs, and pure Python in processes.

[ ]Threads, processes and the GILLocal GPU
import tempfile, textwrap
from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor

# Con spawn (Windows, macOS), cada proceso hijo importa las funciones que ejecuta: tienen que vivir en un módulo.
carpeta = tempfile.mkdtemp(prefix="l23_")
with open(os.path.join(carpeta, "trabajos_l23.py"), "w", encoding="utf-8") as fh:
    fh.write(textwrap.dedent('''
        import numpy as np

        def python_puro(n):
            """Aritmética entera en el intérprete: nunca suelta el GIL."""
            s = 0
            for i in range(n):
                s += (i * i) % 7
            return s

        def con_numpy(n, trozo=1 << 15):
            """Trabajo en ufuncs de NumPy, que sueltan el GIL durante su bucle interno."""
            x = np.linspace(0.0, 1.0, trozo)
            s = 0.0
            for _ in range(n // trozo):
                s += float(np.sin(x * 3.0).sum())
            return s

        def matmuls(args):
            """reps productos n x n con hilos_blas hilos de BLAS dentro de este proceso."""
            hilos_blas, reps, n = args
            from threadpoolctl import threadpool_limits
            A = np.random.default_rng(0).random((n, n))
            with threadpool_limits(limits=hilos_blas, user_api="blas"):
                for _ in range(reps):
                    A @ A
            return reps
    '''))
sys.path.insert(0, carpeta)                      # los hijos creados con spawn reciben el sys.path del padre
import trabajos_l23 as tr

def tiempo(fn, total, p, pool, rep=2):
    """Mejor de rep: crea el pool, reparte total en p tareas iguales y espera a todas."""
    mejor = np.inf
    for _ in range(rep):
        t0 = time.perf_counter()
        with pool(max_workers=p) as ex:
            list(ex.map(fn, [total // p] * p))
        mejor = min(mejor, time.perf_counter() - t0)
    return mejor

N_PY, N_NP = 8_000_000, 1 << 26
base_py = tiempo(tr.python_puro, N_PY, 1, ThreadPoolExecutor)
base_np = tiempo(tr.con_numpy, N_NP, 1, ThreadPoolExecutor)
print(f"secuencial: Python puro {base_py:.2f} s, NumPy {base_np:.2f} s")
print(" p | hilos, Python puro | hilos, NumPy | procesos, Python puro (con arranque)")
for p in (2, 4, 8, 16):
    s1 = base_py / tiempo(tr.python_puro, N_PY, p, ThreadPoolExecutor)
    s2 = base_np / tiempo(tr.con_numpy, N_NP, p, ThreadPoolExecutor)
    s3 = base_py / tiempo(tr.python_puro, N_PY, p, ProcessPoolExecutor)
    print(f"{p:2d} | {s1:18.2f} | {s2:12.2f} | {s3:10.2f}")
t0 = time.perf_counter()
with ProcessPoolExecutor(max_workers=8) as ex:
    list(ex.map(tr.python_puro, [1] * 8))
print(f"crear 8 procesos y hacer 8 tareas vacías: {(time.perf_counter() - t0) * 1e3:.0f} ms")
print("procesos ya arrancados (pool reutilizado), Python puro:")
for p in (4, 8, 16):
    with ProcessPoolExecutor(max_workers=p) as ex:
        list(ex.map(tr.python_puro, [1] * p))      # arranca los p procesos
        t0 = time.perf_counter()
        list(ex.map(tr.python_puro, [N_PY // p] * p))
        print(f"  {p:2d} procesos: speedup {base_py / (time.perf_counter() - t0):.2f}")
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Three columns, three behaviors:

  • Threads with pure Python: speedups between 0.66 and 1.04 with no trend in pp. Threads take turns holding the GIL; variation is noise from shared load and frequency (the sequential measurement’s thread does not always run on the same core type).
  • Threads with NumPy: 2.00, 1.92, 6.00 and 5.62 with 2, 4, 8 and 16 threads. It does speed up because np.sin and sum release the GIL, but stays far from pp and does not grow regularly: with 2152^{15}-element chunks, each loop iteration spends appreciable time in the interpreter with the GIL, an Amdahl ff; remaining irregularity is shared-machine noise.
  • Processes with pure Python: between 0.63 and 0.97 including startup, effectively no gain. Creating 8 processes and doing 8 empty tasks costs 443 ms, nearly the 0.58 s of all work: each child starts an interpreter and imports NumPy. With the pool already started, the same work gives 3.22, 5.13 and 5.71 with 4, 8 and 16 processes. Processes accelerate pure Python only when work per task greatly exceeds startup, or the pool is reused across many tasks, as joblib and a self-play server do.

Monte Carlo: strong, weak and reproducible scaling

The third cell estimates π=∫0141−u2 ⁣du\pi = \int_0^1 4\sqrt{1 - u^2}\dd u with 256 blocks of 2182^{18} samples, one SeedSequence.spawn stream per block, and threads (Generator and ufuncs release the GIL). Each block processes samples in chunks using its own buffer and ufuncs with out=, without temporaries. It measures strong scaling with chunks of 2162^{16} and 2122^{12}, weak scaling with 8 blocks per worker, and checks reproducibility.

[ ]Strong and weak Monte Carlo scaling with threadsLocal GPU
def bloque(semilla, m, trozo=1 << 16):
    """Suma de 4·sqrt(1 − U²) sobre m uniformes del flujo de este bloque (su media es π)."""
    rng = np.random.default_rng(semilla)
    u = np.empty(trozo)
    s = 0.0
    for _ in range(m // trozo):
        rng.random(out=u)                        # sin temporales: todo en el mismo buffer
        np.multiply(u, u, out=u)
        np.subtract(1.0, u, out=u)
        np.sqrt(u, out=u)
        s += u.sum()
    return 4.0 * s

def mc_paralelo(n_bloques, m, workers, semilla=2026, trozo=1 << 16):
    hijos = np.random.SeedSequence(semilla).spawn(n_bloques)    # un flujo por BLOQUE, no por worker
    with ThreadPoolExecutor(workers) as ex:
        sumas = list(ex.map(lambda h: bloque(h, m, trozo), hijos))  # map devuelve en el orden de los bloques
    return sum(sumas) / (n_bloques * m)                           # se combinan siempre en el mismo orden

def mc_por_worker(n, workers, semilla=2026):
    hijos = np.random.SeedSequence(semilla).spawn(workers)      # mal: el reparto depende de workers
    with ThreadPoolExecutor(workers) as ex:
        sumas = list(ex.map(lambda h: bloque(h, n // workers), hijos))
    return sum(sumas) / n

def mejor(f, rep=3):
    t = np.inf
    for _ in range(rep):
        t0 = time.perf_counter(); r = f(); t = min(t, time.perf_counter() - t0)
    return t, r

M = 1 << 18
P_LIST = (1, 2, 4, 8, 12, 16, 24, 32)
fuerte, fuerte_peq, debil, valores = {}, {}, {}, {}
for p in P_LIST:
    fuerte[p], valores[p] = mejor(lambda: mc_paralelo(256, M, p))
    fuerte_peq[p], _ = mejor(lambda: mc_paralelo(256, M, p, trozo=1 << 12))
    debil[p], _ = mejor(lambda: mc_paralelo(8 * p, M, p))
print(f"fuerte: 256 bloques de {M} ({256 * M / 1e6:.0f} M muestras); débil: 8 bloques por worker")
print(" p | trozos 2^16: T (s)  speedup  eficiencia | trozos 2^12: speedup | débil: T (s)  eficiencia")
for p in P_LIST:
    S = fuerte[1] / fuerte[p]
    print(f"{p:2d} | {fuerte[p]:16.3f} {S:8.2f} {S / p:11.2f} | {fuerte_peq[1] / fuerte_peq[p]:20.2f} | "
          f"{debil[p]:12.3f} {debil[1] / debil[p]:11.2f}")
print("π estimado con bloques, igual bit a bit para todo p:", len({valores[p] for p in P_LIST}) == 1, repr(float(valores[1])))
print("con un flujo por worker (1, 4, 16 workers):", [f"{mc_por_worker(64 * M, w):.10f}" for w in (1, 4, 16)])
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Reproducibility is the clean part: with one stream per block, the estimate is 3.141651855309759 with 1, 2, 4, …, 32 workers, bit for bit; with one stream per worker, 3.1421431867, 3.1415432256 and 3.1415743455 with 1, 4 and 16 workers. Performance deserves closer scrutiny:

  • Strong scaling with 2162^{16} chunks. Speedup 2.07, 3.40, 3.94 and 4.34 with 2, 4, 8 and 12 threads, then it falls: 3.95 with 16 and 3.54 with 24 and 32. Monte Carlo is as parallel as a problem can be, so none of this is sequential algorithm work. Each chunk makes five NumPy calls and returns to the interpreter for the GIL between them; with many threads the GIL queue grows and handoffs cost more than the gain. The sequential measurement thread also runs at single-core turbo frequency, higher than the chip sustains with all cores busy.
  • 2122^{12} chunks. With chunks 16 times smaller, GIL-held time weighs 16 times more: 1.37 with 2 threads, 1.65 with 4 and, from 8, slower than one thread (0.55 with 8, 0.51 with 32). This directly demonstrates that Python-thread speedup depends on native work chunk size.
  • Weak scaling. With 8 blocks per worker, time should remain constant; efficiency falls to 0.58 with 4 workers, 0.41 with 8 and 0.08 with 32. With 9 ms work per worker in the one-thread run, pool creation and GIL contention dominate. Good weak scaling needs large native work per task and call.

Repeating the cell changes numbers, especially with many threads, because the reference machine was shared. The pattern remains: modest speedup flattening or falling with Python threads, worse with small chunks, and identical results with per-block streams.

A memory-bound stencil

The fourth cell performs 20 Jacobi iterations of the Laplacian on an 2048×20482048 \times 2048 grid (32 MiB per array) in two ways: Python threads distributing row bands and operating with NumPy in 64-row chunks, and Numba with prange, which never passes through the interpreter. Both give exactly the same result. Each iteration moves at least 24 bytes per point: read u, write v and first fetch the v line (write-allocate).

[ ]Jacobi stencil: Python threads versus NumbaLocal GPU
import numba
from numba import prange

def jacobi(u0, iters, p, filas=64):
    """Jacobi del laplaciano 2D con p hilos: cada hilo actualiza una banda de filas, en trozos de 64 filas
    con un buffer propio (sin temporales nuevos), y todos esperan al final de cada iteración."""
    u, v = u0.copy(), u0.copy()
    n = u.shape[0]
    cortes = np.linspace(1, n - 1, p + 1).astype(int)
    buf = [np.empty((filas, n - 2)) for _ in range(p)]
    def banda(k, a, b):
        t = buf[k]
        for i0 in range(cortes[k], cortes[k + 1], filas):
            i1 = min(i0 + filas, cortes[k + 1])
            tt = t[: i1 - i0]
            np.add(a[i0 - 1:i1 - 1, 1:-1], a[i0 + 1:i1 + 1, 1:-1], out=tt)
            np.add(tt, a[i0:i1, :-2], out=tt)
            np.add(tt, a[i0:i1, 2:], out=tt)
            np.multiply(tt, 0.25, out=b[i0:i1, 1:-1])
    with ThreadPoolExecutor(p) as ex:
        for _ in range(iters):
            list(ex.map(lambda k: banda(k, u, v), range(p)))   # barrera: espera a todas las bandas
            u, v = v, u
    return u

@njit(parallel=True)
def jacobi_numba(u, v, iters):
    """El mismo stencil compilado: prange reparte las filas entre los hilos de Numba, sin GIL."""
    n = u.shape[0]
    for _ in range(iters):
        for i in prange(1, n - 1):
            for j in range(1, n - 1):
                v[i, j] = 0.25 * (u[i - 1, j] + u[i + 1, j] + u[i, j - 1] + u[i, j + 1])
        u, v = v, u
    return u

n, ITERS = 2048, 20
u0 = np.zeros((n, n)); u0[0, :] = 1.0
ref = jacobi(u0, ITERS, 1)
jacobi_numba(u0.copy(), u0.copy(), 1)            # compila
sten, nb = {}, {}
for p in P_LIST:
    sten[p], r = mejor(lambda: jacobi(u0, ITERS, p))
    assert np.array_equal(r, ref)                # cada punto se calcula igual: resultado idéntico
    numba.set_num_threads(p)
    nb[p], r = mejor(lambda: jacobi_numba(u0.copy(), u0.copy(), ITERS))
    assert np.array_equal(r, ref)
numba.set_num_threads(numba.config.NUMBA_NUM_THREADS)
trafico = 3 * 8 * n * n                          # bytes por iteración: leer u, escribir v y traer antes su línea
print(f"stencil {n} x {n}, {ITERS} iteraciones; tráfico mínimo por iteración ~ {trafico / 2**20:.0f} MiB")
print(" p | hilos de Python + NumPy        | Numba prange")
for p in P_LIST:
    print(f"{p:2d} | {sten[p]:.3f} s  x{sten[1] / sten[p]:5.2f}  {trafico * ITERS / sten[p] / 1e9:5.1f} GB/s | "
          f"{nb[p]:.3f} s  x{nb[1] / nb[p]:5.2f}  {trafico * ITERS / nb[p] / 1e9:5.1f} GB/s")
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

The comparison separates two causes of the ceiling. Numba, without the GIL, moves 23.4 GB/s with one thread and 53 to 59 GB/s with 8, 16, 24 and 32 threads, on the order of the 54 GB/s physical traffic lesson 19 measured with STREAM for the whole chip. Its maximum speedup, 2.51 with 24 threads, is simply 58.6/23.458.6/23.4: a memory-bound kernel scales until it saturates memory, and since one thread already moves almost half the chip’s capacity, headroom is small (and noisy: 1.83 with 12 threads and 2.37 with 8). Python threads with NumPy reach 3.01 with 8 threads and 21.4 GB/s, dropping to 2.14 with 32: besides bandwidth, they pay for the GIL between chunks and each iteration’s barrier. Also notice one-thread time: the compiled loop takes 0.086 s and NumPy 0.283 s, 3.3 times more, because it traverses data in four passes with an intermediate buffer. Before parallelizing, use the best sequential program.

Amdahl versus your measurements

The lab’s last cell fits Amdahl’s ff to each speedup curve (least squares in log⁡S\log S, because time errors are relative) and calculates the Karp–Flatt metric at each pp.

[ ]Fitting Amdahl and Karp–FlattLocal GPU
from scipy.optimize import minimize_scalar

def ajusta_f(ps, S):
    """f de Amdahl por mínimos cuadrados en log S (los errores de medida son relativos)."""
    ps, S = np.asarray(ps, float), np.asarray(S, float)
    obj = lambda f: np.sum((np.log(S) - np.log(1 / (f + (1 - f) / ps))) ** 2)
    return minimize_scalar(obj, bounds=(0, 1), method="bounded").x

for nombre, T in (("Monte Carlo, trozos 2^16", fuerte), ("Monte Carlo, trozos 2^12", fuerte_peq),
                  ("stencil, hilos de Python", sten), ("stencil, Numba", nb)):
    ps = np.array([p for p in P_LIST if p > 1])
    S = np.array([T[1] / T[p] for p in ps])
    e = (1 / S - 1 / ps) / (1 - 1 / ps)
    print(f"{nombre}: f ajustada = {ajusta_f(ps, S):.3f}")
    print("   speedups:", "  ".join(f"{p}:{x:.2f}" for p, x in zip(ps, S)))
    print("   Karp-Flatt:", "  ".join(f"{p}:{x:.3f}" for p, x in zip(ps, e)))
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

The fitted ff values are 20% for Monte Carlo with 2162^{16} chunks, 33% for the Python-threaded stencil and 40% for the Numba stencil. For Monte Carlo with 2122^{12} chunks the fit reaches the boundary, f=1f = 1: no f∈[0,1]f \in [0, 1] produces speedup below 1, and from 8 threads the Karp–Flatt metric exceeds 1 (1.72 to 1.97), impossible for a fraction, meaning parallel overhead exceeds all useful work. For Monte Carlo with 2162^{16} chunks and the Python stencil, e(p)e(p) rises steadily from 4 threads (0.059 to 0.259 and 0.143 to 0.449 at 32): costs growing with processors. At 2 threads Monte Carlo’s is even negative, −0.032-0.032, because measured speedup 2.07 exceeds pp: measurement noise, reminding you the metric is sensitive when speedups are close to pp. For the Numba stencil it ranges from 0.34 to 0.51 without a clear trend: this is what Amdahl sees with a fixed ceiling such as bandwidth, an apparent ff near 1/Smax⁡1/S_{\max}. You can put these or your own points into the first figure.

Lab 2: OpenMP, false sharing and scheduling

This lab compiles a small C++ file with OpenMP as a shared library and calls it with ctypes. On Linux it uses g++ -fopenmp; on Windows it finds Visual Studio (or Build Tools) with vswhere, loads the vcvars64.bat environment and compiles with cl /openmp, like compilar in the previous lesson, which compiled the extension’s Lennard-Jones kernel with openmp=True. Here ctypes avoids a pybind11 dependency, but each function can be wrapped in your extension without changing a line of C++: receive an py::array_t, extract pointer and size, release the GIL with py::gil_scoped_release and call the same loop with its #pragma omp. The five functions are a reduction with reduction(+:s), reproducible fixed-block summation, a shared counter with a race, with atomic and with reduction, a false-sharing experiment with configurable counter spacing, and row-wise Mandelbrot with three schedules recording which thread did each row and how long it took.

[ ]Compile OpenMP code and the counter raceLocal GPU
import ctypes, shutil, subprocess
from pathlib import Path

FUENTE = r'''
#include <omp.h>
#include <cstdint>
#ifdef _WIN32
#define API extern "C" __declspec(dllexport)
#else
#define API extern "C"
#endif

// Reducción: cada hilo acumula en su copia privada de s y OpenMP combina las copias al final.
API double suma_omp(const double* x, int64_t n, int hilos) {
    double s = 0.0;
    #pragma omp parallel for reduction(+:s) schedule(static) num_threads(hilos)
    for (int64_t i = 0; i < n; ++i) s += x[i];
    return s;
}

// Suma reproducible: bloques de tamaño fijo B, sumados en paralelo y combinados en orden.
API double suma_bloques(const double* x, int64_t n, int hilos, int64_t B, double* parciales) {
    int64_t nb = (n + B - 1) / B;
    #pragma omp parallel for schedule(static) num_threads(hilos)
    for (int64_t b = 0; b < nb; ++b) {
        double s = 0.0;
        int64_t fin = (b + 1) * B < n ? (b + 1) * B : n;
        for (int64_t i = b * B; i < fin; ++i) s += x[i];
        parciales[b] = s;
    }
    double total = 0.0;
    for (int64_t b = 0; b < nb; ++b) total += parciales[b];   // orden fijo: 0, 1, 2, ...
    return total;
}

// Contador compartido: con carrera (modo 0), con atomic (modo 1) o con reducción (modo 2).
API int64_t contador(int64_t n, int hilos, int modo) {
    if (modo == 0) {
        volatile int64_t c = 0;   // volatile: cada c = c + 1 lee y escribe de verdad en memoria
        #pragma omp parallel for num_threads(hilos)
        for (int64_t i = 0; i < n; ++i) c = c + 1;      // carrera de datos
        return c;
    }
    if (modo == 1) {
        int64_t c = 0;
        #pragma omp parallel for num_threads(hilos)
        for (int64_t i = 0; i < n; ++i) {
            #pragma omp atomic
            c += 1;
        }
        return c;
    }
    int64_t c = 0;
    #pragma omp parallel for reduction(+:c) num_threads(hilos)
    for (int64_t i = 0; i < n; ++i) c += 1;
    return c;
}

// False sharing: el hilo t incrementa n veces su contador, que está en c[t * separacion].
// Incremento normal (atomico = 0, volatile: lee y escribe en memoria cada vez) o atómico (atomico = 1).
// Todos empiezan a la vez tras una barrera; devuelve el tiempo del hilo más lento.
API double contadores(int64_t n, int hilos, int separacion, int64_t* c, int atomico) {
    double peor = 0.0;
    #pragma omp parallel num_threads(hilos)
    {
        int64_t* mio = c + omp_get_thread_num() * separacion;
        volatile int64_t* mio_v = mio;
        #pragma omp barrier
        double t0 = omp_get_wtime();
        if (atomico) {
            for (int64_t i = 0; i < n; ++i) {
                #pragma omp atomic
                *mio += 1;
            }
        } else {
            for (int64_t i = 0; i < n; ++i) *mio_v = *mio_v + 1;
        }
        double t = omp_get_wtime() - t0;
        #pragma omp critical
        { if (t > peor) peor = t; }
    }
    return peor;
}

// Mandelbrot por filas en [-2.1, 0.7] x [-1.25, 1.25] con planificación static, dynamic o guided.
static int64_t fila(int i, int alto, int ancho, int maxit) {
    double ci = -1.25 + 2.5 * i / alto;
    int64_t tot = 0;
    for (int j = 0; j < ancho; ++j) {
        double cr = -2.1 + 2.8 * j / ancho, zr = 0.0, zi = 0.0;
        int k = 0;
        while (k < maxit && zr * zr + zi * zi < 4.0) {
            double t = zr * zr - zi * zi + cr;
            zi = 2.0 * zr * zi + ci;
            zr = t;
            ++k;
        }
        tot += k;
    }
    return tot;
}
#define CUERPO { iters[i] = fila(i, alto, ancho, maxit); quien[i] = omp_get_thread_num(); dur[i] = omp_get_wtime(); }
API double mandelbrot(int alto, int ancho, int maxit, int hilos, int plan, int chunk,
                      int64_t* iters, int* quien, double* dur) {
    double t0 = omp_get_wtime();
    if (plan == 0) {
        #pragma omp parallel for schedule(static) num_threads(hilos)
        for (int i = 0; i < alto; ++i) { double a = omp_get_wtime(); CUERPO dur[i] -= a; }
    } else if (plan == 1) {
        #pragma omp parallel for schedule(dynamic, chunk) num_threads(hilos)
        for (int i = 0; i < alto; ++i) { double a = omp_get_wtime(); CUERPO dur[i] -= a; }
    } else {
        #pragma omp parallel for schedule(guided, chunk) num_threads(hilos)
        for (int i = 0; i < alto; ++i) { double a = omp_get_wtime(); CUERPO dur[i] -= a; }
    }
    return omp_get_wtime() - t0;
}
'''

def entorno_msvc():
    """Variables de entorno de vcvars64.bat (Visual Studio o Build Tools con «Desarrollo para escritorio con C++»)."""
    vswhere = Path(os.environ.get("ProgramFiles(x86)", r"C:\Program Files (x86)")) / "Microsoft Visual Studio" / "Installer" / "vswhere.exe"
    ruta = subprocess.run([str(vswhere), "-latest", "-products", "*", "-property", "installationPath"],
                          capture_output=True, text=True).stdout.strip()
    vcvars = Path(ruta) / "VC" / "Auxiliary" / "Build" / "vcvars64.bat"
    salida = subprocess.run(f'"{vcvars}" >nul && set', shell=True, capture_output=True, text=True).stdout
    return dict(linea.split("=", 1) for linea in salida.splitlines() if "=" in linea)

def compilar(fuente, nombre):
    """Compila fuente como biblioteca compartida con OpenMP y la carga con ctypes."""
    dirc = Path(tempfile.mkdtemp(prefix="omp_"))
    (dirc / f"{nombre}.cpp").write_text(fuente, encoding="utf-8")
    if sys.platform == "win32":
        env = entorno_msvc()
        cl = shutil.which("cl", path=next(v for k, v in env.items() if k.upper() == "PATH"))
        orden, lib = [cl, "/nologo", "/O2", "/openmp", "/LD", f"{nombre}.cpp", f"/Fe:{nombre}.dll"], f"{nombre}.dll"
    else:
        env = None
        orden, lib = ["g++", "-O2", "-fopenmp", "-shared", "-fPIC", f"{nombre}.cpp", "-o", f"{nombre}.so"], f"{nombre}.so"
    r = subprocess.run(orden, cwd=dirc, env=env, capture_output=True, text=True)
    if r.returncode != 0:
        raise RuntimeError(r.stdout + r.stderr)
    return ctypes.CDLL(str(dirc / lib))      # ctypes suelta el GIL durante la llamada

t0 = time.perf_counter()
omp = compilar(FUENTE, "omp_l23")
print(f"compilado y cargado en {time.perf_counter() - t0:.1f} s")
P, I64, I32, D = ctypes.c_void_p, ctypes.c_int64, ctypes.c_int, ctypes.c_double
omp.suma_omp.restype, omp.suma_omp.argtypes = D, [P, I64, I32]
omp.suma_bloques.restype, omp.suma_bloques.argtypes = D, [P, I64, I32, I64, P]
omp.contador.restype, omp.contador.argtypes = I64, [I64, I32, I32]
omp.contadores.restype, omp.contadores.argtypes = D, [I64, I32, I32, P, I32]
omp.mandelbrot.restype, omp.mandelbrot.argtypes = D, [I32] * 6 + [P, P, P]

N = 10_000_000
print("hilos |      con carrera       |   atomic   | reducción")
for h in (1, 2, 4, 8, 16):
    r = []
    for modo in (0, 1, 2):
        t0 = time.perf_counter(); v = omp.contador(N, h, modo); r.append((v, time.perf_counter() - t0))
    print(f"{h:5d} | {r[0][0]:>10,d} ({r[0][0] / N:6.1%}) | {r[1][1] * 1e3:6.0f} ms | {r[2][1] * 1e3:6.2f} ms   "
          f"(atomic y reducción dan {r[1][0]:,d} y {r[2][0]:,d})")
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

With one thread the racing counter reaches ten million; with 2 threads, 59.7%; with 16, 30.7%. Nearly half the increments are lost with just two threads, and the percentage changes between runs (8 threads gave 42.1%, more than 4): it depends on how often threads coincide, not a formula. The atomic version always gives the correct value, but costs 82 ms with one thread, 121 ms with two and 170 ms with 16, slower with more threads, because each increment moves the counter’s cache line between cores. Reduction gives the correct value in hundredths of a millisecond: each thread increments a private variable the compiler can keep in a register (and actually turns the loop into an addition), and only pp numbers are combined at the end. Preference order is reduction, atomic and, if necessary, a lock.

[ ]False sharingLocal GPU
def mide_fs(hilos, sep, atomico=0, n=100_000_000, rep=5):
    """Mediana de rep ejecuciones del tiempo del hilo más lento. Mediana, no mínimo: con la máquina ocupada,
    el mínimo elegiría la ejecución en la que los hilos coincidieron menos, que es la que menos false sharing sufre."""
    c = np.zeros(hilos * 16 + 16, dtype=np.int64)
    ts = []
    for _ in range(rep):
        c[:] = 0
        ts.append(omp.contadores(n, hilos, sep, c.ctypes.data, atomico))
        assert all(c[k * sep] == n for k in range(hilos))
    return float(np.median(ts))

N_AT = 20_000_000                                # el atómico es más lento: menos incrementos
print("      | incremento normal (1e8 por hilo)            | incremento atómico (2e7 por hilo)")
print("hilos | juntos  | a 64 B  | a 128 B | juntos / 64 B | juntos  | a 64 B  | juntos / 64 B")
for h in (1, 2, 4, 8, 16):
    t1, t8, t16 = mide_fs(h, 1), mide_fs(h, 8), mide_fs(h, 16)
    a1, a8 = mide_fs(h, 1, 1, N_AT), mide_fs(h, 8, 1, N_AT)
    print(f"{h:5d} | {t1:5.3f} s | {t8:5.3f} s | {t16:5.3f} s | {t1 / t8:12.1f}x | "
          f"{a1:5.3f} s | {a8:5.3f} s | {a1 / a8:12.1f}x")
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Each thread increments its own counter: one hundred million times with a normal increment, where volatile forces a memory read and write each time (as with a counter other threads inspect), and twenty million with an atomic increment. All threads start together after a barrier and the median of five runs of the slowest thread is taken. In the reference run:

  • With one thread, spacing does not matter: 0.040 s together and 0.039 s at 64 B for normal increment; 0.190 and 0.188 s for atomic.
  • Atomic increment: with counters together, time shoots up with threads (0.688 s with 2, 1.885 s with 8, 3.212 s with 16), while 64 B spacing keeps it between 0.188 and 0.274 s. False-sharing slowdown is 3.3 times with 2 threads, 7.1 with 4, 9.4 with 8 and 11.7 with 16. An x86 lock add needs the line exclusively and drains the core’s write buffer before continuing, so each increment waits for the line: the animation with bursts of 1.
  • Normal increment: the effect exists but is much smaller, 1.1 to 1.8 times (0.144 s together versus 0.082 s separated with 16 threads). Normal writes enter the write buffer and the core continues while waiting for the line; on receiving it, it flushes several in a row. The line changes owners every few writes, as in the long-burst animation.
  • 64 B separation suffices on this processor: the 64 and 128 B columns are almost identical.

These are the false-sharing figure’s bars. The practical lesson is that false sharing hurts most precisely where shared memory is most deliberately used: adjacent atomic counters, locks and per-thread queues.

[ ]OpenMP reduction versus fixed blocksLocal GPU
import math
x = np.random.default_rng(23).normal(size=1 << 24) * np.logspace(0, 8, 1 << 24)
parciales = np.empty((len(x) + 4095) // 4096)
exacta = math.fsum(x)
print("hilos | reduction(+) de OpenMP | bloques fijos de 4096")
for h in (1, 2, 3, 8, 16, 32):
    a_ = omp.suma_omp(x.ctypes.data, len(x), h)
    b_ = omp.suma_bloques(x.ctypes.data, len(x), h, 4096, parciales.ctypes.data)
    print(f"{h:5d} | {a_!r:22} | {b_!r}")
print(f"exacta (math.fsum): {exacta!r}")
del x
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

OpenMP reduction gives five distinct values for 1, 2, 3, 8, 16 and 32 threads (1 and 3 coincide by chance), all within 2.3×10−32.3 \times 10^{-3} of the exact value, −2240709507.831042-2240709507.831042 (relative error at most 10−1210^{-12}). Fixed-block summation gives -2240709507.8308144 for any thread count, 2.3×10−42.3 \times 10^{-4} from exact: almost as accurate as the best reduction (16 threads, 2.0×10−42.0 \times 10^{-4} away), ten times more accurate than the worst and, above all, always identical. This repeats the Pyodide NumPy cell with real threads.

[ ]Mandelbrot: static, dynamic and guidedLocal GPU
alto, ancho, maxit = 1024, 1024, 2000
iters, quien, dur = np.zeros(alto, np.int64), np.zeros(alto, np.int32), np.zeros(alto)

def corre(h, plan, chunk=1, rep=3):
    t = np.inf
    for _ in range(rep):
        t = min(t, omp.mandelbrot(alto, ancho, maxit, h, plan, chunk, iters.ctypes.data, quien.ctypes.data, dur.ctypes.data))
    ocupado = np.bincount(quien, weights=dur, minlength=h)   # tiempo de trabajo de cada hilo (última repetición)
    return t, ocupado.max() / ocupado.mean()

t1, _ = corre(1, 0)
print(f"1 hilo: {t1:.3f} s; iteraciones por fila: mín {iters.min():,d}, máx {iters.max():,d}")
print("hilos | static: speedup, máx/media | dynamic,1 | guided,1 | dynamic,64")
for h in (4, 8, 16, 24, 32):
    cols = [corre(h, plan, c) for plan, c in ((0, 1), (1, 1), (2, 1), (1, 64))]
    print(f"{h:5d} | " + " | ".join(f"{t1 / t:5.2f}x {d:4.2f}" for t, d in cols))
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

The second figure in each column is the ratio of the busiest thread’s work time to the mean: 1.00 is perfect balance. With 24 threads, static gives speedup 8.72 with imbalance 2.60 (the busiest works 2.60 times the mean); dynamic, 1 gives 21.78 with imbalance 1.00; guided, 1, 14.78; and dynamic, 64 only 6.44, because 1024 rows in 64-row blocks make 16 blocks for 24 threads (its imbalance, 3.82, counts the 8 idle threads). This is the scheduling figure’s predicted order: dynamic, 1 near ideal, guided in the middle and static far away.

Absolute speedups need more care. dynamic, 1 with 24 threads exceeds capacity C(24)=8+16⋅0.69≈19.0C(24) = 8 + 16 \cdot 0.69 \approx 19.0 predicted by E-core scalar speed in the first cell, and with 8 threads yields 9.83, above 8, impossible for a kernel that barely touches memory. The deviating quantity is the single-thread baseline: it runs wherever the OS places it and at the frequency the chip gives it, and on a shared machine that measurement is most fragile. Robust comparison is between schedules at the same thread count, sharing the baseline. With 32 threads, dynamic, 1 rises to 23.38: the 8 extra threads are P-cores’ second hardware threads, sharing execution units with the first and contributing little. This kernel, without the GIL, without memory bottlenecks and dynamically scheduled, is the ceiling of what the machine can deliver.

[ ]BLAS oversubscriptionLocal GPU
from threadpoolctl import threadpool_limits, threadpool_info
print("pools de hilos cargados:", [(i["internal_api"], i["num_threads"]) for i in threadpool_info()])
A = np.random.default_rng(0).random((384, 384))

def con_hilos(py, blas, tareas=32, reps=40):
    with threadpool_limits(limits=blas, user_api="blas"):
        t0 = time.perf_counter()
        with ThreadPoolExecutor(py) as ex:
            list(ex.map(lambda _: [A @ A for _ in range(reps)], range(tareas)))
        return time.perf_counter() - t0

def con_procesos(procs, blas, tareas=16, reps=80):
    with ProcessPoolExecutor(procs) as ex:
        list(ex.map(tr.matmuls, [(1, 1, 8)] * procs))          # arranca los procesos antes de medir
        t0 = time.perf_counter()
        list(ex.map(tr.matmuls, [(blas, reps, 384)] * tareas))
        return time.perf_counter() - t0

print("hilos de Python x hilos de BLAS (32 tareas de 40 productos 384 x 384):")
for py, bl in ((1, 1), (1, 24), (8, 24), (24, 24), (8, 1), (24, 1)):
    print(f"  {py:2d} x {bl:2d} = {py * bl:3d} hilos: {con_hilos(py, bl):.2f} s")
print("procesos x hilos de BLAS (16 tareas de 80 productos):")
for pr, bl in ((8, 24), (8, 1)):
    print(f"  {pr:2d} x {bl:2d} = {pr * bl:3d} hilos: {con_procesos(pr, bl):.2f} s")
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

With Python threads, 24-thread BLAS takes nearly the same with 1, 8 or 24 Python threads (1.31, 1.34 and 1.41 s): concurrent calls do not multiply parallel work, but, as the measurement suggests, take turns on the same OpenBLAS thread team. The reverse is faster: 24 Python threads with one BLAS thread each, 0.75 s, 1.75 times faster than letting BLAS distribute each 384×384384 \times 384 product, which is too small to use 24 threads (everything on one thread, 4.32 s). With processes oversubscription is real because each process has its own team: 8 processes with 24 BLAS threads each, 192 threads, take 6.24 s, versus 0.80 s with one BLAS thread per process, almost eight times less. Parallelize at one level: either many tasks with sequential BLAS or one task with parallel BLAS.

Common mistakes

Exercises

NumericAmdahl with 24 cores
95% of a program's time (measured on one core) is perfectly parallelizable and the rest sequential. What speedup does Amdahl's law predict with 24 cores? Give three decimal places.
NumericAmdahl's ceiling
With a 5% sequential fraction, what maximum speedup can any number of cores achieve?
NumericDiagnosing with Karp–Flatt
You measure S(8)=6S(8) = 6 and S(16)=8S(16) = 8. Calculate Karp–Flatt metric e(16)e(16) to three decimal places.
NumericOne execution, two laws
A weakly scaled program spends 5% of its time in a sequential part on 24 cores (that is, s=0.05s = 0.05 in Gustafson's law). If the same workload ran on one core, what fraction ff of its time would be sequential? Give four decimal places.
NumericEqual parts on unequal cores
A processor has 8 P-cores of speed 1 and 16 E-cores of speed 0.5. Perfectly parallelizable work (f=0f = 0) is divided into 24 equal parts, one per core. What speedup results compared with one P-core?
NumericHalf atomic
Two threads each increment shared variable x, initially 0, 10 times. Thread A does so correctly with an indivisible atomic increment (fetch_add). Thread B uses three unprotected steps: read x into its register, add 1 and write the register to x. Operations may interleave arbitrarily. What is the smallest possible final x?
QuizEight threads that do not speed up
A pure Python function performing only integer arithmetic (no NumPy or I/O) is split into 8 equal tasks with ThreadPoolExecutor(8) on a 24-core machine. It takes as long as one thread or slightly longer. Why, and what would you do?
QuizEndless processes on Windows
A script defines trabajo(i) at module level and immediately below, also at module level, opens with ProcessPoolExecutor() as ex: and prints sum(ex.map(trabajo, range(100))). It works on Linux with Python 3.12, but on Windows children fail with a RuntimeError about the “bootstrapping phase” and the pool breaks with BrokenProcessPool (or some launchers keep creating processes). What is missing?
QuizPer-thread counters
An OpenMP C++ program counts events per thread in long long cuenta[16];, with cuenta[omp_get_thread_num()]++ in a hot loop. With 8 threads it is 5 times slower than with 1. There is no race: each thread writes only its own position. Which fixes work? (Several may.)

More than one answer may be correct.

QuizWhich schedule?
You draw a 1024-row Mandelbrot with OpenMP on a processor with 8 P-cores and 16 E-cores, using 24 threads. Central rows cost hundreds of times more than edge rows. Which schedule should take least time?
CodeReproducible parallel Monte Carlo
Implement parallel_mc(f, n, workers, seed=0, block=1 << 14), estimating E[f(U)]\E[f(U)] with U∼Unif⁡[0,1)U \sim \Unif[0, 1) using nn samples distributed across workers threads with concurrent.futures.ThreadPoolExecutor. f receives a NumPy array of uniforms and returns an array of the same size. The result must be bit-for-bit identical for any worker count: divide the nn samples into blocks of block (the last may be shorter), give each block its stream with np.random.SeedSequence(seed).spawn(...) and combine block sums always in the same order. Return a float.
import numpy as np
from concurrent.futures import ThreadPoolExecutor

def parallel_mc(f, n, workers, seed=0, block=1 << 14):
  # Versión ingenua: un flujo por worker. Funciona, pero el resultado depende de workers.
  hijos = np.random.SeedSequence(seed).spawn(workers)
  tam = [n // workers + (1 if w < n % workers else 0) for w in range(workers)]
  def tarea(w):
      u = np.random.default_rng(hijos[w]).random(tam[w])
      return float(np.sum(f(u)))
  with ThreadPoolExecutor(workers) as ex:
      return sum(ex.map(tarea, range(workers))) / n
Shift+Enter to run

Summary

Key idea
CPU parallelism is limited not just by core count, but by what cores share: the sequential part (Amdahl), the interpreter (GIL), memory and cache lines (races, false sharing, bandwidth), and scheduling that ignores unequal tasks and cores.
  • Amdahl (S=1/(f+(1−f)/p)<1/fS = 1/(f + (1 - f)/p) < 1/f) measures strong scaling of a fixed problem; Gustafson (S=p−s(p−1)S = p - s(p - 1)) weak scaling with fixed work per processor. They describe one execution with two normalizations. The Karp–Flatt metric solves for the ff explaining measured speedup; if it grows with pp, a cost grows with processor count.
  • In Python, threads accelerate work outside the interpreter (NumPy, I/O, compiled code releasing the GIL), and processes accelerate pure Python, at startup and serialization cost. With spawn, use guard if __name__ == "__main__" and functions in importable modules. Free-threaded builds (PEP 703) are supported from 3.14, but not by default.
  • OpenMP parallelizes a C++ loop in one line: parallel for, reduction, schedule and private variables.
  • Races lose updates (with two threads, down to a counter of 2); fix with atomics, locks or, better, per-thread reductions. False sharing slows without breaking results; fix by separating each thread’s data. Floating-point reductions vary with thread count; fixed blocks make them reproducible.
  • Bandwidth belongs to the chip: a memory-bound kernel saturates with few threads. Do not oversubscribe: workers times BLAS threads must not exceed cores.
  • With irregular tasks and heterogeneous cores, use dynamic scheduling with many blocks. For reproducible Monte Carlo, use one SeedSequence.spawn stream per fixed-size block and ordered combination.

Next: the GPU takes this to the extreme with thousands of threads sharing memory and cache, in the lesson on its architecture and CUDA programming model; multi-GPU data parallelism generalizes block distribution and reduction across devices.