Wait-Free
Wait-free is not a faster lock-free: it turns a failed CAS from “try again” into “I come after you”, which bounds every thread’s steps, at the cost of more atomics and code that is harder to get right.
Wait-free is not a faster lock-free: it turns a failed CAS from “try again” into “I come after you”, which bounds every thread’s steps, at the cost of more atomics and code that is harder to get right.
stat for the totals, record and report to find the function holding 98% of the samples, annotate to see every sample land on the instruction after an add: a chain of adds, each waiting for the last, and splitting it four ways is …
Whether a spinlock is fast depends on what its waiters do: if every attempt is a read-modify-write, they drag the lock’s line back and forth. Read before you grab, put PAUSE in the loop, back off after losing, and waiting costs …
One tick touches 140 cache lines, and most of the time goes into waiting for them. None of the four steps changes the computation; they change when data arrives, where it lands and who holds it: put the misses in flight together, …
One instruction computes a row of numbers only if the compiler knows how wide a register it may use, is sure nothing overlaps, and is allowed to reorder; when it can’t get all three, intrinsics let you write it yourself, at the …
There are three ways to get data into cache ahead of time, each with a precondition: prefetching needs you to know the address before the hardware does, warming has to happen on the core that reads the data, and double buffering …
How far the compiler can optimize depends on what it can see and what it dares to assume: different types are treated as non-overlapping, an invisible function body means arguments go by the calling convention, and helper macros …
The compiler only makes rewrites it can prove don’t change the result, and it does constant multiplies and divides better than you. What’s left for you is where it lacks information or where the rewrite changes the result: …
A dot-product loop reports “vectorized” at -O3, yet its four additions still wait on each other: floating-point addition isn’t associative, so the compiler won’t reorder it. What loop optimization really asks of you is to spot …
The base class writes the flow and the subclass fills in the details: virtual functions pick the subclass at run time, CRTP at compile time. What you save is more than one indirect jump: the call inlines completely and the object …
Returning a struct by value is usually free, so there’s no need for out-parameters; what to watch are the few patterns that always move or copy. Pure-function attributes are a promise to the compiler: right, and it calls less; …
In a loop like a[i] = *b, the compiler re-reads *b every iteration, because writing a[i] might change it. Pointer optimization is about letting the compiler read less, and fitting linked structures into nearer caches.
The front end has to fetch instructions every cycle, but a branch isn’t resolved until a dozen-plus cycles later, so the CPU guesses. A right guess costs almost nothing; a wrong one throws away everything after it, about 15–20 …
One memory access takes about 100 ns and brings back 64 B. One at a time, that’s 0.64 GB/s, yet one core reading sequentially gets 15–60 GB/s. The missing factor is the number of requests in flight. Whether the next load’s address …
Threads are lighter than processes because the TLB and caches stay usable after the switch, not because the switch itself is cheaper. The TLB has no MESI: when any thread in a process changes the page tables, every core still …
An access never pays for bytes; it pays for cache lines, and the address decides which lines, which cache set they compete for, and which DRAM channel and bank they live on. Part 1 is alignment: why a double aligned to 8 never …
Market data has one producer and several consumers, each of which must see every message, and the producer is the hot path that may not wait for anyone. The answer is a broadcast ring: every slot carries its own sequence stamp, …
MESI enforces one rule: a cache line has either one core that may write it or any number of cores that may only read it, never both. The four states are the answers to two questions — does anyone else hold this line, and have I …
A lock-free SPSC queue works because every shared variable has exactly one writer: each side updates only its own counter and merely reads the other’s. The rest is keeping that property from being quietly undone — a shared element …

Every technique in this post does the same thing at a different layer: move an uncertain, kernel-involving operation off the hot path and force it to happen once, upfront, before it can ambush a single request. An object pool …

The store buffer and the cache-coherence protocol are one piece of hardware, but they create two unrelated engineering problems. One is correctness: does a thread see the right value, in the right order — solved by memory_order …

The enemy of a low-latency system is jitter, not the mean. The goal is to make your hot thread the only thing that will ever run on its core: pinning kills migration cost, the isolation stack evicts the tick / RCU / interrupts one …

What TTT and RTT each cover, why to report p50, p99 and p999 instead of the mean, how marks at thread boundaries separate processing from queueing, and how to use the latency table as a budget.
What a TSC reading means, when it is taken, which core it is taken on, how to record timestamps on the hot path, and how ticks become ns: where the frequency comes from and how to calibrate it yourself.
Who runs first and for how long: scheduling classes and time slices, three traps of real-time priorities, two fixes for priority inversion, why HFT often skips PREEMPT_RT, and which knobs a low-latency box turns from BIOS to …
From one mutex to many producers: condition variables and lost wakeups in a blocking queue, rte_ring’s two pairs of indices and in-order publishing, Disruptor’s availability flags, and whether a full queue should block, drop, or …
AGENTS.md is a README for AI agents: a compact project map that exposes hard rules, build/test commands, verification loops, and deeper documentation links so agents can understand, modify, and verify code without relying on …

Miller-Rabin primality test, Pollard Rho factorisation, Tonelli-Shanks for quadratic residues, cubic residues via F_p[t]/(t^3-a), quartic residues by double square root, and general k-th residues via primitive root + BSGS, plus …
Min_25 sieve: theory, two complete examples, Lagrange interpolation for power sums. Du Jiao sieve: template, P3768, GCD sum, LCM sum.
Greedy optimality for divisibility-chain coin systems, DP over the maximum denomination, and a sieve-style transition by adding one larger coin.
Eratosthenes sieve for μ; g/f/h framework; Conclusions 1 and 2 with derivations and tables; GCD table intuition; CF 803F Coprime Subsequences with bottom-up and Möbius approaches.
Multiplicative functions, single-point and linear-sieve evaluation; Möbius function, both forms of Möbius inversion with full derivations and examples; Dirichlet convolution, key identities, Du Jiao sieve; generalized Möbius …
Seven core techniques for Möbius inversion problems: loop shortening, gcd indicator expansion, coprimality reduction, Dirichlet convolution via T=dk, divisor symmetry, diagonal symmetry, and value-domain cnt[] tricks.
Practice problems for Möbius inversion: LCMSUM, two-variable lcm sum (O(n^3/4)), FSF’s game with offline difference, divisor-count sum d(ij), Omega Numbers with Dirichlet suffix sum.
Divisibility blocking for O(sqrt n) floor-sum evaluation: lemma, single-variable loop, O(1) interval sum requirements, two-variable min-trick, multi-variable pseudocode, and ceiling-division blocking.
GCD/LCM properties, Bézout/Frobenius, Euler’s theorem with power-tower reduction and φ-chain technique, congruence system merging via exGCD, CRT, and n! prime factorisation via Legendre’s formula.
Legendre’s formula, divisor and multiple convolutions in O(n log n), offline-difference batch processing for H(n)=Σf(d)g(⌊n/d⌋).
Hard matrix problems: Fibonacci squared subarray sum with segment-tree 4-tuple and companion matrix; cycle-decomposition partition state space for random-swap sorting, first-step analysis, and Gaussian elimination.
XOR linear basis: full template with kth, range basis, normalisation; Nowcoder median example; CF 1101G prefix-XOR rank; gym 104768 C XOR-divisibility; Simplex LP solver.
Gauss elimination: real/mod/mod-2 templates (solve, det, inv, rank); incremental online RREF; Extended Lights Out, CF 1344F abstract GF(2) modelling, 2024 ICPC Kunming interactive tree queries.
Matrix fast power for linear recurrences (4 patterns), 4 semiring templates (count/bool/min-plus/max-plus), matrix+segment tree for range-add Fibonacci queries, Kitamasa O(k²logn) and NTT O(k log²k logn).
Chromatic polynomial, chordal/interval graphs, PEO product formula, order polynomials (chain/antichain/tree/DAG/divisor lattice), MacMahon formula, Dilworth, Mirsky, Hall’s marriage theorem, Erdős–Szekeres, missile interception.
Newton iteration for polynomial inverse and square root, derivative/integral/composition of formal power series, logarithm and exponential of series, and worked examples including CF438E and a bad-modulus complete-knapsack …
Formal power series basics, ordinary generating functions, inversion identities, generalized binomial expansions, bounded counting examples, and recurrence-to-closed-form examples such as Fibonacci and Catalan.
Order and primitive roots (Euler’s theorem, BSGS, exBSGS), discrete index as logarithm analogue, SGU 261 Discrete Roots, NTT theory and templates, divide-and-conquer NTT (product tree), Wannafly D team selection, Nowcoder 50F …
Polynomial representations, FFT/DFT over complex numbers, Triple Sums, Fuzzy Search (difference convolution), FFT template, Lagrange interpolation (O(n²) and O(n) equidistant), sum of k-th powers, Assigning Prizes polynomial DP.
Cyclic convolution definition, FFT/NTT implementation for n=2^k, zero-padding, why n must be a power of two, and the fold-back technique for arbitrary n.
Cross-correlation via ordinary convolution: reverse-A and reverse-B extraction methods, derivation, and Ring Trick II (cyclic shift score maximisation via difference convolution).
Stars and bars, bounded Diophantine equations via inclusion-exclusion, prefix-sum DP, D&C NTT, equal-cap formula, and a full worked example on CF 2127F.
Hockey Stick identity, addition/multiplication principles, binomial identities, example problems: bitonic sequences, multiset permutations, multi-layer coloring DP, CCPC Subpermutation.
容斥原理的集合与算子形式、有上下界不定方程计数(前缀和DP与分治NTT)、错排公式与第二类斯特林数。
Inclusion-exclusion in set and operator form, equal-count subproblems, bounded Diophantine counting, derangements, Stirling numbers, and selected contest problems.
常见计数结论、Lucas 定理、不定方程解计数、平面分拆、DAG 路径计数、多项式平移、XOR 均匀性与若干竞赛常用结论。
A compact toolkit of geometric sums, floor-sum transformations, XOR facts, Fibonacci identities, and perfect-square patterns.
Nothing in this series yet.