Showing posts with label cpp. Show all posts
Showing posts with label cpp. Show all posts

Nov 15, 2026

[C++][coroutine] compiler annotation

Minimal C++20 examples showing how each Clang coroutine attribute catches a specific bug at compile time.

1. [[clang::coro_return_type]]

Tells Clang that Task represents a coroutine, enabling lifetime analysis across function calls that return it.

// Applied to the coroutine return type itself
struct [[clang::coro_return_type]] Task {
    struct promise_type { /* ... */ };
    ~Task();
};

Task read_name(const std::string& name) {
    co_await something();
    std::cout << name; // Reads `name` after suspension
}

void caller() {
    // Clang warns: temporary std::string("Alice") is destroyed at the semicolon,
    // while `t` still holds a dangling reference to it!
    Task t = read_name("Alice");
} 

2. [[clang::coro_wrapper]]

Applied to a normal (non-coroutine) function that constructs and returns a coro_return_type, so Clang still enforces coroutine temporary-lifetime checks at its call sites.
// Not a coroutine (no co_await/co_return inside), just a factory/wrapper
[[clang::<]]
Task make_reader(const std::string& name) {
    return read_name(name);
}

void caller() {
    // Because of [[clang::<]], Clang still warns about the temporary
    // "Bob" dying before `t` finishes executing!
    Task t = make_reader("Bob");
}

3. [[clang::coro_lifetimebound]] 

Applied to a parameter of a coroutine or wrapper function when standard rules wouldn't automatically know the parameter must outlive the returned coroutine (for example, a raw pointer, std::string_view, or std::span).
// `sv` is passed by value, so Clang normally wouldn't track its underlying buffer.
// [[clang::coro_lifetimebound]] tells Clang the buffer behind `sv` must outlive Task.
Task log_view([[clang::coro_lifetimebound]] std::string_view sv) {
    co_await something();
    std::cout << sv;
}

void caller() {
    // Clang warns: temporary std::string dies at ';', leaving `sv` dangling inside `t`
    Task t = log_view(std::string("temporary"));
}

4. [[clang::coro_only_destroy_when_complete]] 

Applied to a coro_return_type whose destructor expects the coroutine to have reached final_suspend (not destroyed mid-suspension, which can leak resources or skip cleanup).
struct [[clang::coro_return_type, clang::coro_only_destroy_when_complete]] StrictTask {
    struct promise_type { /* ... */ };
    ~StrictTask(); // Calls handle.destroy() assuming coroutine already finished
};

StrictTask work() {
    co_await something();
}

void caller() {
    StrictTask t = work(); // Suspends at `something()`
} // Clang warns: `t` is destroyed at scope exit without ever being awaited/completed!

Nov 9, 2026

[C++] coding tricks/tips from talk "A Metaprogramming Checklist - Ben Deane - C++Now 2026"

Reference:
https://www.youtube.com/watch?v=6n_mOFP_kBA

Marking operator= as const breaks conventional value semantics, but serves three distinct, intentional architectural patterns:

  • Compile-Time DSLs & Tag Parameters: Allows constexpr or immutable global tag instances to produce configuration/option pairs without mutating the tag itself:


template <typename T>
struct SettingOption {
    const char* key;
    T value;
};

template <typename T>
struct SettingKey {
    const char* name;

    // operator= does NOT modify *this; it constructs and returns an option pair
    constexpr SettingOption<T> operator=(T val) const {
        return SettingOption<T>{name, val};
    }
};

// Global immutable tag
inline constexpr SettingKey<int> timeout{"timeout_ms"};
inline constexpr SettingKey<bool> verbose{"verbose"};

// Usage:
void configure(SettingOption<int> opt);

int main() {
    // 'timeout' is const/constexpr, but 'timeout = 1000' is valid
    configure(timeout = 1000);
}
  • Proxy References & Shallow-Const Semantics: For views, handles, or memory-mapped hardware abstractions, the proxy itself remains bitwise identical (its address/handle does not change), but writes propagate through to the underlying resource:
struct HardwareReg {
    volatile uint32_t* addr;
    void operator=(uint32_t val) const noexcept { *addr = val; }
};
  • Internally Synchronized / Thread-Safe Types: Under C++11 Core Guidelines, const denotes thread safety (safe to call concurrently without external locking). An assignment operating purely on internal atomics or mutable std::mutex states can qualify as const.(For ordinary value types, avoid operator= const—use lvalue ref-qualifiers (operator=(...) &) instead to guard against unintended temporary assignment).

Why Use requires true in C++20?

At first glance, requires true looks completely redundant.
However, in C++20, attaching any requires clause—even one that unconditionally evaluates to true—changes how the compiler handles a function during explicit template instantiation, overload resolution, and friend function generation. 

1. Skipping Member Functions During Explicit Class Instantiation
Normally, class template member functions are lazily instantiated only when called. However, explicitly instantiating a class template (e.g., template struct Wrapper;) forces the compiler to eagerly instantiate every unconstrained non-template member function body immediately. If a type T does not support an operation inside one of those helper functions, compilation fails even if that function is never called.

Under the C++20 standard ([temp.explicit]/8), explicit class instantiation ignores constrained member functions. Adding requires true keeps the member function lazy during explicit class instantiation without requiring a complex concept definition.
#include <iostream>

template <typename T>
struct Wrapper {
    T value;

    // Without 'requires true', 'template struct Wrapper<NoPrint>;' fails to compile
    // because NoPrint has no operator<<.
    void debug_print() requires true {
        std::cout << value << '\n';
    }
};

struct NoPrint {};

// Explicitly instantiate Wrapper<NoPrint>.
// Compiles cleanly ONLY because debug_print() is constrained with 'requires true'.
template struct Wrapper<NoPrint>;

int main() {
    Wrapper<NoPrint> w; // Valid as long as w.debug_print() is never called

    Wrapper<int> wi{42};
    wi.debug_print();   // Instantiated on demand; prints 42
}

2. Overriding an Unconstrained Template in Overload Resolution 
If a third-party library or legacy header provides an unconstrained function template, defining another function template with the exact same signature normally causes a redefinition error (if in the same scope) or an ambiguous call error. Under C++20 partial ordering rules ([temp.func.order]), a constrained template is strictly more specialized than an unconstrained template. Adding requires true allows a new generic implementation to cleanly beat the unconstrained baseline in overload resolution for all types T, without restricting which types are accepted.

#include <iostream>

// (1) Unconstrained baseline (e.g., from a legacy header)
template <typename T>
void serialize(const T&) {
    std::cout << "Unconstrained baseline\n";
}

// (2) Constrained with 'requires true'
// Beats (1) in overload resolution for every type T.
template <typename T>
requires true
void serialize(const T&) {
    std::cout << "Preferred generic implementation\n";
}

int main() {
    serialize(123);     // Calls (2)
    serialize("hello"); // Calls (2)
} 

3. Avoiding Redefinition Errors in Non-Dependent Hidden Friends 
When defining a non-template friend function inline inside a class template, if the friend's parameter types do not depend directly on the class template parameter T, the compiler treats the friend as an ordinary function. Instantiating the class template with two different types (e.g., Derived and Derived) will define the exact same function twice and fail with a redefinition error. Under C++20 ([temp.friend]/9), a constrained non-template friend function is uniquely tied to its enclosing class template specialization, giving each specialization its own distinct friend entity and preventing redefinition errors when multiple specializations are instantiated.

#include <iostream>

struct Base {};

template <typename T>
struct Derived : Base {
    // Without 'requires true', instantiating Derived<int> and Derived<double>
    // fails to compile with a redefinition error of 'void ping(const Base&)'.
    // With 'requires true', each specialization gets its own unique friend entity.
    friend void ping(const Base&) requires true {
        std::cout << "ping\n";
    }
};

int main() {
    Derived<int> d1;
    Derived<double> d2; // Compiles cleanly with no redefinition error

    // Note: Only works while a single specialization is instantiated in the TU;
    // once two exist, calling ping(d1) becomes ambiguous between Derived<int>::ping
    // and Derived<double>::ping because both take 'const Base&'.
} 
Use Case Without requires true With requires true
Explicit Class Instantiation
template struct Foo<T>;
Eagerly instantiates all member function bodies, failing if T lacks required operations. Skips instantiating the member function body until it is explicitly called ([temp.explicit]/11).
Overloading Identical Template Signatures Causes a redefinition or ambiguous overload error. Wins overload resolution over the unconstrained template via partial ordering ([temp.func.order]).
Non-Dependent Inline Friend in Class Template Causes a redefinition error when the class template is instantiated with multiple types. Ties the friend entity to the enclosing class specialization ([temp.friend]/9).

Nov 6, 2026

[concepts] C++20 Concept Trap of std::inserter and std::array

Reference:
https://github.com/Jimmy-Hu/TinyDIP/discussions/2

When writing generic C++20 function templates that populate an output container—using std::inserter for dynamic containers (std::vector, std::deque, std::list) and falling back to overwriting elements via std::ranges::begin for fixed-size containers (std::array<T, N>)—combining if constexpr with a C++20 concept seems straightforward.

However, pairing legacy C++98 iterator adaptors (std::inserter) with C++20 requires-expressions creates a subtle two-layer compile-time trap where std::array falsely satisfies insertion concepts.


Trap 1: Checking std::inserter Construction

The most intuitive way to check if a container supports std::inserter is testing whether std::inserter(x, std::ranges::end(x)) is well-formed:

template<typename T>
concept naive_is_inserterable = requires(T& x) {
    std::inserter(x, std::ranges::end(x));
};

Why it fails: 

naive_is_inserterable> evaluates to true.
std::inserter merely constructs a std::insert_iterator proxy object that stores a pointer to the container and an iterator. It does not check whether .insert() exists on the container during construction. 

When std::array enters the if constexpr branch, the algorithm later invokes operator=, triggering a hard compiler error ('insert': is not a member of 'std::array<...>'). 

Trap 2: Simulating Assignment (*std::inserter(...) = v) 

Because the actual .insert() call lives inside std::insert_iterator::operator=, the next logical attempt is simulating an element assignment inside the requires-expression:
template<typename T>
concept assign_is_inserterable = std::ranges::range<T> and requires(
    T& x, std::ranges::range_value_t<T> v) {
    
    *std::inserter(x, std::ranges::end(x)) = v;
};

Why it still fails: 

assign_is_inserterable> still evaluates to true for two reasons: 
  1. Unevaluated Operands ([expr.prim.req]): Expressions inside a requires block are unevaluated.
    The compiler only checks whether the declaration signature of std::insert_iterator::operator= matches the argument types in the immediate context without instantiating the function body.
  2. Unconstrained Signature & Non-Deduced Return Type:
    std::insert_iterator::operator=(const typename Container::value_type&) has an explicit return type (insert_iterator&, not auto) and lacks a C++20 requires constraint of its own.
    Since std::array provides both iterator and value_type member types, the declaration matches cleanly without the compiler ever inspecting container->insert(iter, value) inside the body.

The Solution:

Verifying x.insert(...) in the Immediate Context To force the compiler to verify insertion support during concept evaluation, the requires-expression must test x.insert(...) directly on the container alongside std::inserter:
template<typename T>
concept is_inserterable = std::ranges::range<T> and requires(
    T& x, std::ranges::range_value_t<T> v) {
    x.insert(std::ranges::end(x), v);
    std::inserter(x, std::ranges::end(x));
};

With x.insert(...) exposed in the immediate context of the requires clause, is_inserterable> properly evaluates to false, allowing if constexpr to safely route std::array to the fixed-size overwrite branch:
template<typename OutputContainer, std::ranges::input_range InputRange>
constexpr OutputContainer populate_doubled(const InputRange& input) {
    OutputContainer output{};
    auto double_op = [](const auto val) { return val * 2; };

    if constexpr (is_inserterable<OutputContainer>) {
        std::ranges::transform(input, std::inserter(output, std::ranges::end(output)), double_op);
    } else {
        std::ranges::transform(input, std::ranges::begin(output), double_op);
    }
    return output;
}

Key Takeaways 

Iterator adaptors hide container requirements: 
Legacy C++98 output iterator adaptors (std::insert_iterator, std::back_insert_iterator, std::front_insert_iterator) defer the actual container mutation (insert, push_back, push_front) to unconstrained operator= bodies. 

Test underlying operations directly: 
When writing C++20 concepts to gate iterator adaptors, always constrain on the container's member function (x.insert(...), x.push_back(...)) in the immediate context rather than relying on the adaptor's construction or assignment expression.
template<typename T>
concept is_inserterable = std::ranges::range<T> and requires(
    T& x, std::ranges::range_value_t<T> v) {
    x.insert(std::ranges::end(x), v);
    std::inserter(x, std::ranges::end(x));
};

With x.insert(...) exposed in the immediate context of the requires clause, is_inserterable> properly evaluates to false, allowing if constexpr to safely route std::array to the fixed-size overwrite branch:
template<typename OutputContainer, std::ranges::input_range InputRange>
constexpr OutputContainer populate_doubled(const InputRange& input) {
    OutputContainer output{};
    auto double_op = [](const auto val) { return val * 2; };

    if constexpr (is_inserterable<OutputContainer>) {
        std::ranges::transform(input, std::inserter(output, std::ranges::end(output)), double_op);
    } else {
        std::ranges::transform(input, std::ranges::begin(output), double_op);
    }
    return output;
}

Key Takeaways
Iterator adaptors hide container requirements:
Legacy C++98 output iterator adaptors (std::insert_iterator, std::back_insert_iterator, std::front_insert_iterator) defer the actual container mutation (insert, push_back, push_front) to unconstrained operator= bodies. 

Test underlying operations directly:
When writing C++20 concepts to gate iterator adaptors, always constrain on the container's member function (x.insert(...), x.push_back(...)) in the immediate context rather than relying on the adaptor's construction or assignment expression.

Nov 2, 2026

[C++] ternary conditional operator

Reference:
[kernnel][C][C++] ternary conditional operator trick in action
Lightning Talk: ?: - Jonathan Müller - C++Now 2026

#include <iostream>
#include <type_traits>

int main() {
    bool cond = true;

    // 1. cond ? -1 : 1
    // Both operands are int, so the resulting type is int.
    auto r1 = cond ? -1 : 1;
    static_assert(std::is_same_v<decltype(r1), int>);

    // 2. cond ? -1 : 87654321
    // Both operands fit in int (decimal literal without suffix is int), resulting in int.
    auto r2 = cond ? -1 : 87654321;
    static_assert(std::is_same_v<decltype(r2), int>);

    // 3. cond ? -1 : 0x87654321
    // On systems with 32-bit int, 0x87654321 exceeds INT_MAX (2,147,483,647).
    // Hexadecimal integer literals without suffixes take the first type in:
    // int -> unsigned int -> long int -> unsigned long int ... that can represent the value.
    // Thus, 0x87654321 is typed as `unsigned int`.
    // By the usual arithmetic conversions for the ternary operator, 
    // int (-1) is converted to unsigned int, yielding an unsigned result.
    auto r3 = cond ? -1 : 0x87654321;
    static_assert(std::is_same_v<decltype(r3), unsigned int>);

    std::cout << "r1: " << r1 << " (type: int)\n";
    std::cout << "r2: " << r2 << " (type: int)\n";
    std::cout << "r3: " << r3 << " (type: unsigned int, value: " << r3 << ")\n";

    return 0;
}

#include <iostream>
#include <cstdint>
#include <type_traits>

int main() {
    bool cond = true;

    // 1. cond ? 'a' : 1
    // 'a' has type char, and 1 has type int.
    // By the usual arithmetic conversions, char is promoted to int.
    auto r1 = cond ? 'a' : 1;
    static_assert(std::is_same_v<decltype(r1), int>);

    // 2. cond ? 'a' : short(11)
    // Types smaller than int (here char and short) undergo integral promotion
    // to int before determining the common type, resulting in int.
    auto r2 = cond ? 'a' : short(11);
    static_assert(std::is_same_v<decltype(r2), int>);

    // 3. cond ? std::uint8_t(1) : std::int8_t(-1)
    // Both uint8_t and int8_t promote to int because int can represent 
    // all values of both types (0..255 and -128..127).
    auto r3 = cond ? std::uint8_t(1) : std::int8_t(-1);
    static_assert(std::is_same_v<decltype(r3), int>);

    std::cout << "r1: " << r1 << " (type: int)\n";
    std::cout << "r2: " << r2 << " (type: int)\n";
    std::cout << "r3: " << r3 << " (type: int)\n";

    return 0;
}

#include <iostream>
#include <type_traits>

enum A { a1, a2 };
enum B { b1, b2 };

int main() {
    bool cond = true;

    // 1. cond ? a1 : a2
    // Both operands are of the exact same unscoped enum type `A`,
    // so the resulting common type remains `A`.
    auto r1 = cond ? a1 : a2;
    static_assert(std::is_same_v<decltype(r1), A>);

    // 2. cond ? a1 : 11
    // One operand is enum `A` and the other is `int`.
    // Unscoped enums undergo integral promotion to their underlying type / `int`.
    // The common type resolves to `int`.
    auto r2 = cond ? a1 : 11;
    static_assert(std::is_same_v<decltype(r2), int>);

    // 3. cond ? a1 : b1
    // The operands are of distinct unscoped enum types `A` and `B`.
    // Both undergo integral promotions to `int` via the usual arithmetic conversions,
    // resulting in `int`.
    auto r3 = cond ? a1 : b1;
    static_assert(std::is_same_v<decltype(r3), int>);

    std::cout << "r1: " << r1 << " (type: A)\n";
    std::cout << "r2: " << r2 << " (type: int)\n";
    std::cout << "r3: " << r3 << " (type: int)\n";

    return 0;
}

#include <iostream>
#include <type_traits>

enum A { a1, a2 };

// "We have `std::constant_wrapper` at home"[cite: 4]
template <auto V>
using constant = std::integral_constant<decltype(V), V>;

int main() {
    bool cond = true;

    // 1. cond ? constant<0> : constant<0>
    // Both operands are the exact same type: constant<0>.
    auto r1 = cond ? constant<0>{} : constant<0>{};
    static_assert(std::is_same_v<decltype(r1), constant<0>>);

    // 2. cond ? constant<0> : constant<1>
    // Distinct types: std::integral_constant provides `constexpr operator value_type()`.
    // Both convert implicitly to int, so overload resolution selects int.
    auto r2 = cond ? constant<0>{} : constant<1>{};
    static_assert(std::is_same_v<decltype(r2), int>);

    // 3. cond ? constant<a1> : constant<a1>
    // Both operands are the exact same type: constant<a1>.
    auto r3 = cond ? constant<a1>{} : constant<a1>{};
    static_assert(std::is_same_v<decltype(r3), constant<a1>>);

    // 4. cond ? constant<a1> : constant<a2>
    // Both operands provide conversion operators to `A` (`operator A()`).
    // However, built-in conditional operator candidates [over.built] only exist 
    // for pointers, pointer-to-members, scoped enumerations, and promoted arithmetic types.
    // Because `A` is an unscoped enumeration, it undergoes integral promotion,
    // making `int operator?:(bool, int, int)` the candidate chosen, resulting in `int`.
    auto r4 = cond ? constant<a1>{} : constant<a2>{};
    static_assert(std::is_same_v<decltype(r4), int>);

    std::cout << "r1 type: constant<0>\n";
    std::cout << "r2 type: int\n";
    std::cout << "r3 type: constant<a1>\n";
    std::cout << "r4 type: int\n";

    return 0;
}

#include <iostream>
#include <cstdint>
#include <type_traits>

template <auto V>
using constant = std::integral_constant<decltype(V), V>;

int main() {
    bool cond = true;

    // 1. cond ? constant<'a'> : constant<short(11)>
    // Both operands are distinct types. Their implicit conversion operators
    // yield `char` and `short`, which both undergo integral promotion to `int`.
    // The built-in candidate `int operator?:(bool, int, int)` is selected.
    auto r1 = cond ? constant<'a'>{} : constant<short(11)>{};
    static_assert(std::is_same_v<decltype(r1), int>);

    // 2. cond ? constant<std::uint8_t(1)> : constant<std::int8_t(-1)>
    // Operands implicitly convert to `std::uint8_t` and `std::int8_t`.
    // Both types promote to `int` via the usual arithmetic conversions,
    // resulting in `int`.
    auto r2 = cond ? constant<std::uint8_t(1)>{} : constant<std::int8_t(-1)>{};
    static_assert(std::is_same_v<decltype(r2), int>);

    // 3. cond ? constant<std::uint8_t(1)> : constant<std::uint8_t(2)>
    // Even though both convert to the same underlying type (std::uint8_t),
    // they are distinct class template instantiations. Overload resolution for 
    // the conditional operator considers built-in candidate operators [over.built].
    // Built-in candidates exist only for promoted arithmetic types (at least `int`),
    // not for small types like `std::uint8_t`, so the common result type promotes to `int`.
    auto r3 = cond ? constant<std::uint8_t(1)>{} : constant<std::uint8_t(2)>{};
    static_assert(std::is_same_v<decltype(r3), int>);

    std::cout << "r1: " << r1 << " (type: int)\n";
    std::cout << "r2: " << r2 << " (type: int)\n";
    std::cout << "r3: " << r3 << " (type: int)\n";

    return 0;
}

#include <iostream>
#include <type_traits>
#include <utility>

int main() {
    bool cond = true;
    int i = 0;
    const int ci = 0;

    // 1. cond ? i : ci -> const int&
    // Both operands are lvalues differing only in cv-qualification.
    // The result is an lvalue of the cv-combined type (const int), yielding `const int&` under decltype.
    decltype(auto) r1 = cond ? i : ci; //[cite: 6]
    static_assert(std::is_same_v<decltype(cond ? i : ci), const int&>); //[cite: 6]

    // 2. cond ? std::move(i) : std::move(ci) -> const int&&
    // Both operands are xvalues (rvalue references) differing only in cv-qualification.
    // The result is an xvalue of the cv-combined type (const int), yielding `const int&&` under decltype.
    decltype(auto) r2 = cond ? std::move(i) : std::move(ci); //[cite: 6]
    static_assert(std::is_same_v<decltype(cond ? std::move(i) : std::move(ci)), const int&&>); //[cite: 6]

    // 3. cond ? i : std::move(ci) -> int
    // One operand is an lvalue (`int&`) and the other is an xvalue (`const int&&`).
    // Because value categories differ and cannot bind to a common reference category directly,
    // lvalue-to-rvalue conversion is applied to both, resulting in a prvalue of type `int`.
    decltype(auto) r3 = cond ? i : std::move(ci); //[cite: 6]
    static_assert(std::is_same_v<decltype(cond ? i : std::move(ci)), int>); //[cite: 6]

    std::cout << "r1: " << r1 << " (type: const int&)\n";
    std::cout << "r2: " << r2 << " (type: const int&&)\n";
    std::cout << "r3: " << r3 << " (type: int)\n";

    return 0;
}

Oct 30, 2026

[clang] Thread Safety Analysis

https://clang.llvm.org/docs/ThreadSafetyAnalysis.html


The page documents Clang's compile-time race checker for C++. You annotate which lock protects which data, and the compiler warns when code touches that data without holding the lock. The check is static: no runtime cost, and it is not a runtime tool like TSan.

Enabling it
Compile with -Wthread-safety.
Google code uses the ABSL_* macros from absl/base/thread_annotations.h. The page itself defines its own macros in a sample mutex.h.

The core idea: capabilities
A capability is anything that acts as a lock (a mutex, for example). You mark the lock class with CAPABILITY("mutex"), whose older spelling is lockable.
A thread holds a capability either exclusively (writing allowed) or shared (reading only).
The analysis tracks, at every point in a function, which capabilities the thread holds.

Main annotations
Annotation Meaning
GUARDED_BY(mu) You must hold mu to read (shared) or write (exclusive) this member.
PT_GUARDED_BY(mu) Same rule, but for the data the pointer points to.
REQUIRES(mu) / REQUIRES_SHARED(mu) Callers must already hold mu when they call this function.
ACQUIRE(mu) / RELEASE(mu) The function locks or unlocks mu.
TRY_ACQUIRE(true, mu) The function locks mu only if it returns the given value.
EXCLUDES(mu) Callers must not hold mu (prevents deadlock on non-reentrant locks).
SCOPED_CAPABILITY Marks an RAII lock class (like MutexLock) that locks in its constructor and unlocks in its destructor.
ASSERT_CAPABILITY(mu) Tells the analysis that mu is held from here on (the function checks at runtime).
RETURN_CAPABILITY(mu) The function returns a reference to mu (for getters).
ACQUIRED_BEFORE / ACQUIRED_AFTER Declares the order locks must be taken in. Only checked under -Wthread-safety-beta.
NO_THREAD_SAFETY_ANALYSIS Turns the check off for one function.


Negative capabilities
With -Wthread-safety-negative, REQUIRES(!mu) states that the caller must not hold mu. This catches deadlocks more strictly than EXCLUDES.

Warning flags
-Wthread-safety is the umbrella flag. It turns on -attributes, -analysis, and -precise.
-Wthread-safety-reference and -Wthread-safety-beta add stricter or still-experimental checks.

Known limitations
  • Each function is checked on its own. The analysis does not look inside callees, so it relies on their annotations.
  • It does not track aliases. If two pointers refer to the same mutex, the analysis treats them as different locks.
  • Conditional locking (if (x) mu.Lock(); ... if (x) mu.Unlock();) produces warnings.
  • Constructors and destructors are not checked.
  • Lock ordering is only partly enforced.

Example
class Account {
  Mutex mu;
  int balance GUARDED_BY(mu);
  void Deposit(int x) {
    balance += x;      // warning: writing 'balance' requires holding 'mu' exclusively
  }
  void SafeDeposit(int x) {
    MutexLock l(&mu);  // SCOPED_CAPABILITY
    balance += x;      // OK
  }
};

Oct 4, 2026

[c++23] coroutine with deducing this

C++23 Deducing this: 

A standard C++20 IILE (Immediately Invoked Lambda Expression) coroutine [=](){...}() captures the temporary closure by reference, causing an immediate dangling reference once the statement evaluates. Using the explicit object parameter (this auto) forces the closure and its captures to be passed by value into the coroutine frame, binding their lifetime to the coroutine state.

operator->* Overload: 

Replaces the easily missed trailing (); of an IILE. The operator evaluates left-to-right, perfectly forwarding and immediately invoking the callable. This shifts the execution trigger to the head of the block for immediate visual parsing.

ASYNC Macro: 

Fuses the invocation trick and deducing this into a zero-overhead DSL. It enforces explicit captures (__VA_ARGS__) and strictly defines the promise return type (Coro), completely hiding the C++23 boilerplate.

Execution Flow: 

pool_task always suspends initially. The thread pool queue stores this initial handle. The queue must never automatically repush the handle after resumption; continuation is strictly deferred to the awaited operation's await_suspend logic to prevent catastrophic spin-loops.

class thread_pool {
    queue<std::coroutine_handle<>> work;
    // ...
};

void thread_pool::submit(auto awaitable) {
    // Used after free bug due to capture in anonymous type instance.
    auto task = [=]() -> pool_task {
        // always suspends initially
        co_await awaitable;
        // destroys itself in final suspend
    }();
    work.push(task.handle());
}

Deduce this with copy by value; NOT capture by value.
void thread_pool::submit(auto awaitable) {
    auto task = lambda_invoker() ->* [=](this auto) -> pool_task {
        co_await awaitable;
    };
    work.push(task.handle());
}

struct lambda_invoker {
    auto operator->*(auto&& fn) {
        return std::forward<decltype(fn)>(fn)();
    }
};

Use ->* operator with macro.
void thread_pool::submit(auto awaitable) {
    auto task = ASYNC(pool_task, awaitable) {
        co_await awaitable;
    };
    work.push(task.handle());
}

struct lambda_invoker {
    auto operator->*(auto&& fn) {
        return std::forward<decltype(fn)>(fn)();
    }
};

#define ASYNC(Coro, ...) \
    lambda_invoker() ->* [__VA_ARGS__](this auto) -> Coro
    

Oct 2, 2026

[coroutine] c9 idiom of cancellation.

1. Who creates the coroutine?
             ↓
2. Who owns the coroutine_handle?
             ↓
3. Who resumes it?
             ↓
4. What event causes the resume?
             ↓
5. Who destroys the frame?

// Minimal single-threaded model of C9-style cancellation.
//
// Key difference from the stop_token version: a cancelled coroutine is NEVER
// resumed. The cancel callback destroys every frame of the logical thread
// (leaf -> entry), running destructors, and then resumes an "on_exit" handle
// so the owner learns the thread is gone. No code checks a token.
//
// Name map to google3/util/c9/internal:
//   PromiseLink      -> CoroutinePromiseLink (waiter link, co_thread)
//   CoThread         -> CoThread (cancelled_ AsyncNotification, on_exit)
//   SuspensionToken  -> SuspensionToken (BecameReady/Cancelled/AlreadyCancelled,
//                       DestroyCallStack)
//   Scheduler        -> ThreadState ready queue + Schedule/CancelWaiter
//   Yield / CondVar  -> leaf awaitables like c9::Event::Awaitable

#include <algorithm>
#include <coroutine>
#include <deque>
#include <exception>
#include <functional>
#include <iostream>
#include <optional>
#include <type_traits>
#include <utility>

struct FrameCounter {
  static inline int live = 0;
  FrameCounter() { ++live; }
  ~FrameCounter() { --live; }
};

class CoThread;

// Base of every Co<T> promise. The `waiter` pointers form the intrusive
// "coroutine call stack" that cancellation walks and destroys.
struct PromiseLink {
  std::coroutine_handle<> self;    // this frame
  PromiseLink* waiter = nullptr;   // caller frame; nullptr for the entry frame
  CoThread* co_thread = nullptr;   // logical thread this frame belongs to
};

// One logical thread of execution = one chain of nested co_awaits.
class CoThread {
 public:
  explicit CoThread(std::coroutine_handle<> on_exit) : on_exit_(on_exit) {}

  std::coroutine_handle<> on_exit() const { return on_exit_; }

  // Called by the leaf awaitable while suspending. False = already cancelled,
  // so the leaf must not park; it must destroy the stack instead.
  bool Register(std::function<void()> on_cancel) {
    if (cancelled_) return false;
    on_cancel_ = std::move(on_cancel);
    return true;
  }
  void Unregister() { on_cancel_ = nullptr; }

  // Request cancellation. If a leaf is parked, its callback runs now and
  // destroys the whole chain. If the chain is currently running, nothing
  // happens here; it dies at its next suspension point (Register -> false).
  void Cancel() {
    cancelled_ = true;
    if (on_cancel_) std::exchange(on_cancel_, nullptr)();
  }

 private:
  std::coroutine_handle<> on_exit_;
  bool cancelled_ = false;
  std::function<void()> on_cancel_;
};

// Handed to a leaf awaitable at suspension. Exactly one of BecameReady,
// Cancelled, AlreadyCancelled is called for each suspension.
class SuspensionToken {
 public:
  explicit SuspensionToken(PromiseLink* leaf) : leaf_(leaf) {}

  bool operator==(const SuspensionToken&) const = default;

  bool RegisterForCancellation(std::function<void()> on_cancel) {
    return co_thread().Register(std::move(on_cancel));
  }

  // Normal wakeup: stop listening for cancel; caller resumes the leaf.
  std::coroutine_handle<> BecameReady() {
    co_thread().Unregister();
    return leaf_->self;
  }

  // Cancel callback won the race: destroy the chain, tell the owner. The leaf
  // coroutine is never resumed.
  void Cancelled() {
    std::coroutine_handle<> on_exit = co_thread().on_exit();  // read first
    DestroyCallStack();                                       // frees leaf_
    on_exit.resume();
  }

  // Register failed (cancelled before we could park): destroy the chain and
  // return on_exit for the caller to symmetric-transfer into.
  std::coroutine_handle<> AlreadyCancelled() {
    std::coroutine_handle<> on_exit = co_thread().on_exit();
    DestroyCallStack();
    return on_exit;
  }

 private:
  CoThread& co_thread() { return *leaf_->co_thread; }

  // Callee before caller, iteratively, so OS stack depth stays O(1).
  void DestroyCallStack() {
    for (PromiseLink* p = leaf_; p != nullptr;) {
      PromiseLink* next = p->waiter;
      p->self.destroy();  // runs this frame's destructors (RAII)
      p = next;
    }
  }

  PromiseLink* leaf_;
};

// Ready queue of wakeups. Holds tokens, not raw handles, so BecameReady runs
// (unregistering the cancel callback) right before resume.
class Scheduler {
 public:
  void Schedule(SuspensionToken t) { ready_.push_back(t); }

  // Pull a scheduled wakeup back out so the frame can be destroyed instead.
  // False = already dequeued and running; cancellation then takes effect at
  // the coroutine's next suspension point.
  bool CancelWaiter(const SuspensionToken& t) {
    return std::erase(ready_, t) > 0;
  }

  void Run() {
    while (!ready_.empty()) {
      SuspensionToken t = ready_.front();
      ready_.pop_front();
      t.BecameReady().resume();
    }
  }

 private:
  std::deque<SuspensionToken> ready_;
};

// Awaitable child coroutine. Lazy start, symmetric transfer, frame destroys
// itself at final_suspend (result is written into the parent's frame first).
template <typename T>
class Co {
  static constexpr bool kVoid = std::is_void_v<T>;
  struct Empty {};
  using Slot = std::conditional_t<kVoid, Empty, std::optional<T>>;

  template <typename U>
  struct ReturnValue {
    std::optional<U>* result = nullptr;  // lives in the awaiting parent
    void return_value(U v) { result->emplace(std::move(v)); }
  };
  struct ReturnVoid {
    void return_void() {}
  };

 public:
  struct promise_type
      : PromiseLink,
        FrameCounter,
        std::conditional_t<kVoid, ReturnVoid, ReturnValue<T>> {
    Co get_return_object() {
      auto h = std::coroutine_handle<promise_type>::from_promise(*this);
      this->self = h;
      return Co(h);
    }
    std::suspend_always initial_suspend() noexcept { return {}; }
    auto final_suspend() noexcept {
      struct Final {
        bool await_ready() noexcept { return false; }
        std::coroutine_handle<> await_suspend(
            std::coroutine_handle<promise_type> h) noexcept {
          PromiseLink* waiter = h.promise().waiter;
          std::coroutine_handle<> on_exit = h.promise().co_thread->on_exit();
          h.destroy();  // frame gone; only locals used from here on
          return waiter != nullptr ? waiter->self : on_exit;
        }
        void await_resume() noexcept {}
      };
      return Final{};
    }
    void unhandled_exception() { std::terminate(); }
  };

  explicit Co(std::coroutine_handle<promise_type> h) : h_(h) {}
  Co(Co&& o) noexcept : h_(std::exchange(o.h_, {})) {}
  ~Co() {
    if (h_) h_.destroy();  // only if never started
  }

  bool await_ready() const noexcept { return false; }
  template <typename P>
  std::coroutine_handle<> await_suspend(std::coroutine_handle<P> parent) {
    promise_type& p = h_.promise();
    p.waiter = &parent.promise();
    p.co_thread = parent.promise().co_thread;
    if constexpr (!kVoid) p.result = &result_;
    return std::exchange(h_, {});  // frame now owns itself
  }
  T await_resume() {
    if constexpr (!kVoid) return std::move(*result_);
  }

  // For bridges only: hand the entry frame to a new CoThread.
  std::coroutine_handle<promise_type> Release() {
    return std::exchange(h_, {});
  }

 private:
  std::coroutine_handle<promise_type> h_;
  Slot result_;
};

// Tiny coroutine used as a CoThread's on_exit handle.
struct OnExit {
  struct promise_type : FrameCounter {
    OnExit get_return_object() {
      return {std::coroutine_handle<promise_type>::from_promise(*this)};
    }
    std::suspend_always initial_suspend() noexcept { return {}; }
    std::suspend_never final_suspend() noexcept { return {}; }
    void return_void() {}
    void unhandled_exception() { std::terminate(); }
  };
  std::coroutine_handle<> handle;
};

OnExit ReportExit(const char* name) {
  std::cout << name << ": thread exited\n";
  co_return;
}

// Bridge: start `co` as the entry frame of a fresh CoThread (what C9 bridges,
// RunConcurrently and WithDeadline do for their children).
void Spawn(Scheduler& sched, CoThread& ct, Co<void> co) {
  auto h = co.Release();
  h.promise().co_thread = &ct;  // waiter stays nullptr: entry frame
  sched.Schedule(SuspensionToken(&h.promise()));
}

// ---- Leaf awaitables (the only place cancellation is "implemented") ----

// Re-queue the current coroutine (simulates work). Cancellable.
class Yield {
 public:
  explicit Yield(Scheduler& s) : sched_(s) {}
  bool await_ready() const noexcept { return false; }
  template <typename P>
  std::coroutine_handle<> await_suspend(std::coroutine_handle<P> h) {
    token_.emplace(&h.promise());
    if (!token_->RegisterForCancellation([this] { Cancel(); })) {
      return token_->AlreadyCancelled();
    }
    sched_.Schedule(*token_);
    return std::noop_coroutine();
  }
  void await_resume() const noexcept {}

 private:
  void Cancel() {
    // Copy out: Cancelled() destroys the frame that holds *this.
    Scheduler& sched = sched_;
    SuspensionToken token = *token_;
    if (sched.CancelWaiter(token)) token.Cancelled();
  }
  Scheduler& sched_;
  std::optional<SuspensionToken> token_;
};

// Condition variable. Note Wait() takes no token: cancellation is implicit.
class CondVar {
 public:
  explicit CondVar(Scheduler& sched) : sched_(sched) {}

  class Awaiter {
   public:
    explicit Awaiter(CondVar& cv) : cv_(cv) {}
    bool await_ready() const noexcept { return false; }
    template <typename P>
    std::coroutine_handle<> await_suspend(std::coroutine_handle<P> h) {
      token_.emplace(&h.promise());
      if (!token_->RegisterForCancellation([this] { Cancel(); })) {
        return token_->AlreadyCancelled();
      }
      cv_.waiters_.push_back(*token_);
      return std::noop_coroutine();
    }
    void await_resume() const noexcept {}

   private:
    void Cancel() {
      CondVar& cv = cv_;
      SuspensionToken token = *token_;
      // Either still parked here, or NotifyOne already moved it to the ready
      // queue. Pull it back from wherever it is, then destroy.
      if (std::erase(cv.waiters_, token) > 0 || cv.sched_.CancelWaiter(token)) {
        token.Cancelled();
      }
    }
    CondVar& cv_;
    std::optional<SuspensionToken> token_;
  };

  Awaiter Wait() { return Awaiter(*this); }

  void NotifyOne() {
    if (waiters_.empty()) return;
    sched_.Schedule(waiters_.front());
    waiters_.pop_front();
  }

 private:
  Scheduler& sched_;
  std::deque<SuspensionToken> waiters_;
};

// ---- User code: no token anywhere ----

class Channel {
 public:
  explicit Channel(Scheduler& sched) : cv_(sched) {}
  void Push(int v) {
    items_.push_back(v);
    cv_.NotifyOne();
  }
  Co<int> Pop() {
    while (items_.empty()) co_await cv_.Wait();
    int v = items_.front();
    items_.pop_front();
    co_return v;
  }

 private:
  std::deque<int> items_;
  CondVar cv_;
};

Co<void> Consumer(Scheduler& sched, Channel& ch, int id) {
  struct Cleanup {
    int id;
    ~Cleanup() { std::cout << "consumer " << id << " cleanup (RAII)\n"; }
  } cleanup{id};

  for (;;) {  // no exit path: cancellation destroys this frame instead
    int item = co_await ch.Pop();
    std::cout << "consumer " << id << " processes " << item << "\n";
    co_await Yield(sched);
  }
}

Co<void> Producer(Scheduler& sched, Channel& ch) {
  for (int i = 0;; ++i) {
    std::cout << "producer pushes " << i << "\n";
    ch.Push(i);
    co_await Yield(sched);
  }
}

Co<void> StopAfter(Scheduler& sched, std::deque<CoThread*> threads, int ticks) {
  for (int i = 0; i < ticks; ++i) co_await Yield(sched);
  std::cout << "=== cancel requested ===\n";
  for (CoThread* t : threads) t->Cancel();  // callbacks destroy the stacks
}

int main() {
  Scheduler sched;
  Channel ch(sched);

  CoThread c1(ReportExit("consumer 1").handle);
  CoThread c2(ReportExit("consumer 2").handle);
  CoThread prod(ReportExit("producer").handle);
  CoThread stopper(ReportExit("stopper").handle);

  Spawn(sched, c1, Consumer(sched, ch, 1));
  Spawn(sched, c2, Consumer(sched, ch, 2));
  Spawn(sched, prod, Producer(sched, ch));
  Spawn(sched, stopper, StopAfter(sched, {&c1, &c2, &prod}, 3));

  sched.Run();

  std::cout << "live coroutine frames after Run(): " << FrameCounter::live
            << "\n";
  return FrameCounter::live == 0 ? 0 : 1;
}

Sep 29, 2026

[coroutine] event/notify example


#include <coroutine>
#include <deque>
#include <exception>
#include <iostream>
#include <utility>

// Single-threaded scheduler: a queue of coroutines ready to resume.
class Scheduler {
 public:
  void Schedule(std::coroutine_handle<> h) {
    std::cout << "  [queue push_back " << h.address() << "]\n";
    ready_.push_back(h);
  }

  void Run() {
    while (!ready_.empty()) {
      std::coroutine_handle<> h = ready_.front();
      ready_.pop_front();
      std::cout << "  [queue pop_front -> resume " << h.address() << "]\n";
      h.resume();
    }
  }

 private:
  std::deque<std::coroutine_handle<>> ready_;
};

// Coroutine condition variable. Wait() parks the handle;
// Notify*() moves parked handles to the scheduler's ready queue.
class CondVar {
 public:
  explicit CondVar(Scheduler& sched) : sched_(sched) {}

  auto Wait() {
    struct Awaiter {
      CondVar& cv;
      bool await_ready() const noexcept { return false; }
      void await_suspend(std::coroutine_handle<> h) {
        std::cout << "  [cv parks " << h.address() << "]\n";
        cv.waiters_.push_back(h);
      }
      void await_resume() const noexcept {}
    };
    return Awaiter{*this};
  }

  void NotifyOne() {
    if (waiters_.empty()) return;
    sched_.Schedule(waiters_.front());
    waiters_.pop_front();
  }

  void NotifyAll() {
    while (!waiters_.empty()) NotifyOne();
  }

 private:
  Scheduler& sched_;
  std::deque<std::coroutine_handle<>> waiters_;
};

// Fire-and-forget top-level coroutine (unchanged from the original).
struct Task {
  struct promise_type {
    Task get_return_object() { return {}; }
    std::suspend_never initial_suspend() noexcept { return {}; }
    std::suspend_never final_suspend() noexcept { return {}; }
    void return_void() {}
    void unhandled_exception() { std::terminate(); }
  };
};

// Awaitable child coroutine: lazy start + symmetric transfer both ways.
struct Co {
  struct promise_type {
    std::coroutine_handle<> continuation;  // parent to resume when done

    Co get_return_object() {
      return Co{std::coroutine_handle<promise_type>::from_promise(*this)};
    }
    // Don't run until the parent co_awaits us (so continuation is set).
    std::suspend_always initial_suspend() noexcept { return {}; }

    auto final_suspend() noexcept {
      struct Final {
        bool await_ready() noexcept { return false; }
        std::coroutine_handle<> await_suspend(
            std::coroutine_handle<promise_type> h) noexcept {
          return h.promise().continuation;  // jump straight back to parent
        }
        void await_resume() noexcept {}
      };
      return Final{};
    }
    void return_void() {}
    void unhandled_exception() { std::terminate(); }
  };

  explicit Co(std::coroutine_handle<promise_type> h) : h_(h) {}
  Co(Co&& o) noexcept : h_(std::exchange(o.h_, {})) {}
  ~Co() {
    if (h_) h_.destroy();  // frame lives until the co_await expression ends
  }

  bool await_ready() const noexcept { return false; }
  std::coroutine_handle<> await_suspend(std::coroutine_handle<> parent) {
    h_.promise().continuation = parent;
    return h_;  // jump straight into child; no queue
  }
  void await_resume() const noexcept {}

  std::coroutine_handle<promise_type> h_;
};

bool data_ready = false;

Co WaitForData(CondVar& cv, int id) {
  while (!data_ready) {  // Predicate loop, same as std::condition_variable.
    std::cout << "child " << id << " waits\n";
    co_await cv.Wait();
  }
  std::cout << "child " << id << " sees data\n";
}

Task Consumer(CondVar& cv, int id) {
  std::cout << "consumer " << id << " calls child\n";
  co_await WaitForData(cv, id);  // nested co_await
  std::cout << "consumer " << id << " woke up\n";
}

Task Producer(CondVar& cv) {
  data_ready = true;
  std::cout << "producer notifies\n";
  cv.NotifyAll();
  co_return;
}

int main() {
  Scheduler sched;
  CondVar cv(sched);
  Consumer(cv, 1);
  Consumer(cv, 2);
  Producer(cv);
  std::cout << "--- sched.Run() ---\n";
  sched.Run();
}


In a C++20 coroutine, a suspension point is any location where the coroutine can pause execution, save its local state to the heap-allocated coroutine frame, and return control to its caller or resumer.

There are four types of suspension points, split between those you write explicitly in the function body and those the compiler injects automatically around your code.


Where They Live: Compiler Transformation

When write a coroutine, the C++20 compiler rewrites its body into a state machine wrapped in boilerplate that invokes your promise_type. Every coroutine contains at least the two implicit suspension points, plus any explicit ones we write:



// What the compiler generates behind the scenes for your coroutine:
{
    promise_type promise;
    auto return_object = promise.get_return_object();

    // --- 1. IMPLICIT: Initial Suspension Point ---
    co_await promise.initial_suspend();

    try {
        // --- YOUR COROUTINE BODY STARTS HERE ---
        
        // --- 2. EXPLICIT: co_await Suspension Point ---
        auto data = co_await async_read();

        // --- 3. EXPLICIT: co_yield Suspension Point ---
        co_yield data; // Rewritten as: co_await promise.yield_value(data);

        // co_return is NOT a suspension point; it sets the result and jumps to final_suspend
        co_return;     // Calls promise.return_void() and goto final_suspend;
        
        // --- YOUR COROUTINE BODY ENDS HERE ---
    } catch (...) {
        promise.unhandled_exception();
    }

final_suspend:
    // --- 4. IMPLICIT: Final Suspension Point ---
    co_await promise.final_suspend();
} // Coroutine frame is automatically destroyed here ONLY if final_suspend does not suspend

Does a Suspension Point Always Suspend?

Hitting a suspension point means the coroutine may suspend, not that it must suspend. At every co_await (including those generated by co_yield, initial_suspend, and final_suspend), the compiler queries an Awaiter object using a 3-step protocol:

  1. awaiter.await_ready(): Checked first as a fast-path optimization.

    • If it returns true, the result is already available. The coroutine does not suspend and immediately calls await_resume().

    • If it returns false, the coroutine prepares to suspend by saving its instruction pointer and local registers into the coroutine frame.

  2. awaiter.await_suspend(handle): Called right after the coroutine state is saved. Its return type controls what happens next:

    • void: Truly suspends the coroutine and returns control to the caller/resumer.

    • bool: Returning true suspends and returns to the caller; returning false aborts the suspension and immediately resumes the coroutine on the current thread.

    • std::coroutine_handle: Suspends the current coroutine and immediately resumes the returned handle via symmetric transfer (without growing the call stack).

  3. awaiter.await_resume(): Called once the coroutine is resumed (or immediately if await_ready() returned true). Its return value becomes the result of the co_await expression.


#include <coroutine>
#include <deque>
#include <exception>
#include <iostream>
#include <optional>
#include <stop_token>
#include <utility>

// Counts live coroutine frames so main() can prove nothing leaked.
struct FrameCounter {
  static inline int live = 0;
  FrameCounter() { ++live; }
  ~FrameCounter() { --live; }
};<

// Single-threaded scheduler: a queue of coroutines ready to resume.
class Scheduler {
 public:
  void Schedule(std::coroutine_handle<> h) { ready_.push_back(h); }

  // Returns when no coroutine is runnable. After a stop request, that means
  // every task has exited (graceful shutdown), unless one is stuck on
  // something that ignores the stop token.
  void Run() {
    while (!ready_.empty()) {
      std::coroutine_handle<> h = ready_.front();
      ready_.pop_front();
      h.resume();
    }
  }

 private:
  std::deque<std::coroutine_handle<>> ready_;
};

// Re-queues the current coroutine so others get a turn (simulates work).
auto Yield(Scheduler& sched) {
  struct Awaiter {
    Scheduler& sched;
    bool await_ready() const noexcept { return false; }
    void await_suspend(std::coroutine_handle<> h) { sched.Schedule(h); }
    void await_resume() const noexcept {}
  };
  return Awaiter{sched};
}

// Coroutine condition variable with cancellation.
// Wait(token) parks the handle. It is woken by NotifyOne/NotifyAll OR by
// token's stop request, whichever comes first. Callers must re-check their
// predicate and the token after waking (same as std::condition_variable_any).
class CondVar {
 public:
  explicit CondVar(Scheduler& sched) : sched_(sched) {}

  class WaitAwaiter {
   public:
    WaitAwaiter(CondVar& cv, std::stop_token token)
        : cv_(cv), token_(std::move(token)) {}

    // Already stopped: don't suspend at all.
    bool await_ready() const noexcept { return token_.stop_requested(); }

    void await_suspend(std::coroutine_handle<> h) {
      h_ = h;
      cv_.waiters_.push_back(h);
      // Runs OnStop inline if stop was already requested. The callback is
      // deregistered when this awaiter is destroyed (end of co_await).
      on_stop_.emplace(token_, OnStop{this});
    }

    void await_resume() const noexcept {}

   private:
    struct OnStop {
      WaitAwaiter* self;
      void operator()() const noexcept { self->cv_.CancelWait(self->h_); }
    };

    CondVar& cv_;
    std::stop_token token_;
    std::coroutine_handle<> h_;
    std::optional<std::stop_callback<OnStop>> on_stop_;
  };

  WaitAwaiter Wait(std::stop_token token) {
    return WaitAwaiter(*this, std::move(token));
  }

  void NotifyOne() {
    if (waiters_.empty()) return;
    sched_.Schedule(waiters_.front());
    waiters_.pop_front();
  }

  void NotifyAll() {
    while (!waiters_.empty()) NotifyOne();
  }

 private:
  // Wakes h only if it is still parked here. If NotifyOne already moved it
  // to the ready queue, do nothing; scheduling it twice would resume a
  // coroutine that is not suspended (UB).
  void CancelWait(std::coroutine_handle<> h) {
    for (auto it = waiters_.begin(); it != waiters_.end(); ++it) {
      if (*it == h) {
        waiters_.erase(it);
        sched_.Schedule(h);
        return;
      }
    }
  }

  Scheduler& sched_;
  std::deque<std::coroutine_handle<>> waiters_;
};

// Fire-and-forget top-level coroutine. Frame self-destroys at the end.
struct Task {
  struct promise_type : FrameCounter {
    Task get_return_object() { return {}; }
    std::suspend_never initial_suspend() noexcept { return {}; }
    std::suspend_never final_suspend() noexcept { return {}; }
    void return_void() {}
    void unhandled_exception() { std::terminate(); }
  };
};

// Awaitable child coroutine returning T: lazy start + symmetric transfer.
template <typename T>
class Co {
 public:
  struct promise_type : FrameCounter {
    std::coroutine_handle<> continuation;  // parent to resume when done
    std::optional<T> result;

    Co get_return_object() {
      return Co(std::coroutine_handle<promise_type>::from_promise(*this));
    }
    std::suspend_always initial_suspend() noexcept { return {}; }
    auto final_suspend() noexcept {
      struct Final {
        bool await_ready() noexcept { return false; }
        std::coroutine_handle<> await_suspend(
            std::coroutine_handle<promise_type> h) noexcept {
          return h.promise().continuation;  // jump straight back to parent
        }
        void await_resume() noexcept {}
      };
      return Final{};
    }
    void return_value(T v) { result.emplace(std::move(v)); }
    void unhandled_exception() { std::terminate(); }
  };

  explicit Co(std::coroutine_handle<promise_type> h) : h_(h) {}
  Co(Co&& o) noexcept : h_(std::exchange(o.h_, {})) {}
  ~Co() {
    if (h_) h_.destroy();
  }

  bool await_ready() const noexcept { return false; }
  // Parent 就是之後的 await_resume resume 的handle.
  // await_suspend 吃的handle就是await_resume resume的handle.
  std::coroutine_handle<> await_suspend(std::coroutine_handle<> parent) {
    h_.promise().continuation = parent;
    return h_;  // jump straight into child; no queue
  }
  
  // await_suspend 吃的handle就是await_resume resume的handle.
  // co_await 回傳值在此. 
  // 若 coroutune function return的type 也為 waitable
  // 其promise_type::void return_value(T v) 會將return value儲存至
  // promise_type, 其final_suspend() return waitable type會resume parent 
  // 跳至此await_resume().
  T await_resume() { return std::move(*h_.promise().result); }

 private:
  std::coroutine_handle<promise_type> h_;
};

// Unbounded work queue.
class Channel {
 public:
  explicit Channel(Scheduler& sched) : cv_(sched) {}

  void Push(int v) {
    items_.push_back(v);
    cv_.NotifyOne();
  }

  // Graceful semantics: keeps handing out queued items even after stop, and
  // returns nullopt only when the queue is empty AND stop was requested.
  Co<std::optional<int>> Pop(std::stop_token token) {
    while (items_.empty()) {
      if (token.stop_requested()) co_return std::nullopt;
      co_await cv_.Wait(token);  // nested co_await; parks THIS child frame
    }
    int v = items_.front();
    items_.pop_front();
    co_return v;
  }

 private:
  std::deque<int> items_;
  CondVar cv_;
};

Task Consumer(Scheduler& sched, Channel& ch, int id, std::stop_token token) {
  struct Cleanup {  // proves destructors run on shutdown
    int id;
    ~Cleanup() { std::cout << "consumer " << id << " cleanup (RAII)\n"; }
  } cleanup{id};

  while (std::optional<int> item = co_await ch.Pop(token)) {
    std::cout << "consumer " << id << " processes " << *item << "\n";
    co_await Yield(sched);  // simulate work
  }
  std::cout << "consumer " << id << " exits\n";
}

Task Producer(Scheduler& sched, Channel& ch, std::stop_token token) {
  for (int i = 0; !token.stop_requested(); ++i) {
    std::cout << "producer pushes " << i << "\n";
    ch.Push(i);
    co_await Yield(sched);
  }
  std::cout << "producer exits (stop requested)\n";
}

// Stands in for a SIGTERM handler / deadline: requests stop after `ticks`.
Task StopAfter(Scheduler& sched, std::stop_source& stop, int ticks) {
  for (int i = 0; i < ticks; ++i) co_await Yield(sched);
  std::cout << "=== shutdown requested ===\n";
  stop.request_stop();  // wakes parked waiters via their stop_callbacks
}

int main() {
  Scheduler sched;
  Channel ch(sched);
  std::stop_source stop;

  Consumer(sched, ch, 1, stop.get_token());
  Consumer(sched, ch, 2, stop.get_token());
  Producer(sched, ch, stop.get_token());
  StopAfter(sched, stop, 3);

  sched.Run();  // returns once every task has exited

  std::cout << "live coroutine frames after Run(): " << FrameCounter::live
            << "\n";
  return FrameCounter::live == 0 ? 0 : 1;
}

// Minimal single-threaded model of C9-style cancellation.
//
// Key difference from the stop_token version: a cancelled coroutine is NEVER
// resumed. The cancel callback destroys every frame of the logical thread
// (leaf -> entry), running destructors, and then resumes an "on_exit" handle
// so the owner learns the thread is gone. No code checks a token.
//
// Name map to google3/util/c9/internal:
//   PromiseLink      -> CoroutinePromiseLink (waiter link, co_thread)
//   CoThread         -> CoThread (cancelled_ AsyncNotification, on_exit)
//   SuspensionToken  -> SuspensionToken (BecameReady/Cancelled/AlreadyCancelled,
//                       DestroyCallStack)
//   Scheduler        -> ThreadState ready queue + Schedule/CancelWaiter
//   Yield / CondVar  -> leaf awaitables like c9::Event::Awaitable

#include <algorithm>
#include <coroutine>
#include <deque>
#include <exception>
#include <functional>
#include <iostream>
#include <optional>
#include <type_traits>
#include <utility>

struct FrameCounter {
  static inline int live = 0;
  FrameCounter() { ++live; }
  ~FrameCounter() { --live; }
};

class CoThread;

// Base of every Co<T> promise. The `waiter` pointers form the intrusive
// "coroutine call stack" that cancellation walks and destroys.
struct PromiseLink {
  std::coroutine_handle<> self;    // this frame
  PromiseLink* waiter = nullptr;   // caller frame; nullptr for the entry frame
  CoThread* co_thread = nullptr;   // logical thread this frame belongs to
};

// One logical thread of execution = one chain of nested co_awaits.
class CoThread {
 public:
  explicit CoThread(std::coroutine_handle<> on_exit) : on_exit_(on_exit) {}

  std::coroutine_handle<> on_exit() const { return on_exit_; }

  // Called by the leaf awaitable while suspending. False = already cancelled,
  // so the leaf must not park; it must destroy the stack instead.
  bool Register(std::function<void()> on_cancel) {
    if (cancelled_) return false;
    on_cancel_ = std::move(on_cancel);
    return true;
  }
  void Unregister() { on_cancel_ = nullptr; }

  // Request cancellation. If a leaf is parked, its callback runs now and
  // destroys the whole chain. If the chain is currently running, nothing
  // happens here; it dies at its next suspension point (Register -> false).
  void Cancel() {
    cancelled_ = true;
    if (on_cancel_) std::exchange(on_cancel_, nullptr)();
  }

 private:
  std::coroutine_handle<> on_exit_;
  bool cancelled_ = false;
  std::function<void()> on_cancel_;
};

// Handed to a leaf awaitable at suspension. Exactly one of BecameReady,
// Cancelled, AlreadyCancelled is called for each suspension.
class SuspensionToken {
 public:
  explicit SuspensionToken(PromiseLink* leaf) : leaf_(leaf) {}

  bool operator==(const SuspensionToken&) const = default;

  bool RegisterForCancellation(std::function<void()> on_cancel) {
    return co_thread().Register(std::move(on_cancel));
  }

  // Normal wakeup: stop listening for cancel; caller resumes the leaf.
  std::coroutine_handle<> BecameReady() {
    co_thread().Unregister();
    return leaf_->self;
  }

  // Cancel callback won the race: destroy the chain, tell the owner. The leaf
  // coroutine is never resumed.
  void Cancelled() {
    std::coroutine_handle<> on_exit = co_thread().on_exit();  // read first
    DestroyCallStack();                                       // frees leaf_
    on_exit.resume();
  }

  // Register failed (cancelled before we could park): destroy the chain and
  // return on_exit for the caller to symmetric-transfer into.
  std::coroutine_handle<> AlreadyCancelled() {
    std::coroutine_handle<> on_exit = co_thread().on_exit();
    DestroyCallStack();
    return on_exit;
  }

 private:
  CoThread& co_thread() { return *leaf_->co_thread; }

  // Callee before caller, iteratively, so OS stack depth stays O(1).
  void DestroyCallStack() {
    for (PromiseLink* p = leaf_; p != nullptr;) {
      PromiseLink* next = p->waiter;
      p->self.destroy();  // runs this frame's destructors (RAII)
      p = next;
    }
  }

  PromiseLink* leaf_;
};

// Ready queue of wakeups. Holds tokens, not raw handles, so BecameReady runs
// (unregistering the cancel callback) right before resume.
class Scheduler {
 public:
  void Schedule(SuspensionToken t) { ready_.push_back(t); }

  // Pull a scheduled wakeup back out so the frame can be destroyed instead.
  // False = already dequeued and running; cancellation then takes effect at
  // the coroutine's next suspension point.
  bool CancelWaiter(const SuspensionToken& t) {
    return std::erase(ready_, t) > 0;
  }

  void Run() {
    while (!ready_.empty()) {
      SuspensionToken t = ready_.front();
      ready_.pop_front();
      t.BecameReady().resume();
    }
  }

 private:
  std::deque<SuspensionToken> ready_;
};

// Awaitable child coroutine. Lazy start, symmetric transfer, frame destroys
// itself at final_suspend (result is written into the parent's frame first).
template <typename T>
class Co {
  static constexpr bool kVoid = std::is_void_v<T>;
  struct Empty {};
  using Slot = std::conditional_t<kVoid, Empty, std::optional<T>>;

  template <typename U>
  struct ReturnValue {
    std::optional<U>* result = nullptr;  // lives in the awaiting parent
    void return_value(U v) { result->emplace(std::move(v)); }
  };
  struct ReturnVoid {
    void return_void() {}
  };

 public:
  struct promise_type
      : PromiseLink,
        FrameCounter,
        std::conditional_t<kVoid, ReturnVoid, ReturnValue<T>> {
    Co get_return_object() {
      auto h = std::coroutine_handle<promise_type>::from_promise(*this);
      this->self = h;
      return Co(h);
    }
    std::suspend_always initial_suspend() noexcept { return {}; }
    auto final_suspend() noexcept {
      struct Final {
        bool await_ready() noexcept { return false; }
        std::coroutine_handle<> await_suspend(
            std::coroutine_handle<promise_type> h) noexcept {
          PromiseLink* waiter = h.promise().waiter;
          std::coroutine_handle<> on_exit = h.promise().co_thread->on_exit();
          h.destroy();  // frame gone; only locals used from here on
          return waiter != nullptr ? waiter->self : on_exit;
        }
        void await_resume() noexcept {}
      };
      return Final{};
    }
    void unhandled_exception() { std::terminate(); }
  };

  explicit Co(std::coroutine_handle<promise_type> h) : h_(h) {}
  Co(Co&& o) noexcept : h_(std::exchange(o.h_, {})) {}
  ~Co() {
    if (h_) h_.destroy();  // only if never started
  }

  bool await_ready() const noexcept { return false; }
  template <typename P>
  std::coroutine_handle<> await_suspend(std::coroutine_handle<P> parent) {
    promise_type& p = h_.promise();
    p.waiter = &parent.promise();
    p.co_thread = parent.promise().co_thread;
    if constexpr (!kVoid) p.result = &result_;
    return std::exchange(h_, {});  // frame now owns itself
  }
  T await_resume() {
    if constexpr (!kVoid) return std::move(*result_);
  }

  // For bridges only: hand the entry frame to a new CoThread.
  std::coroutine_handle<promise_type> Release() {
    return std::exchange(h_, {});
  }

 private:
  std::coroutine_handle<promise_type> h_;
  Slot result_;
};

// Tiny coroutine used as a CoThread's on_exit handle.
struct OnExit {
  struct promise_type : FrameCounter {
    OnExit get_return_object() {
      return {std::coroutine_handle<promise_type>::from_promise(*this)};
    }
    std::suspend_always initial_suspend() noexcept { return {}; }
    std::suspend_never final_suspend() noexcept { return {}; }
    void return_void() {}
    void unhandled_exception() { std::terminate(); }
  };
  std::coroutine_handle<> handle;
};

OnExit ReportExit(const char* name) {
  std::cout << name << ": thread exited\n";
  co_return;
}

// Bridge: start `co` as the entry frame of a fresh CoThread (what C9 bridges,
// RunConcurrently and WithDeadline do for their children).
void Spawn(Scheduler& sched, CoThread& ct, Co<void> co) {
  auto h = co.Release();
  h.promise().co_thread = &ct;  // waiter stays nullptr: entry frame
  sched.Schedule(SuspensionToken(&h.promise()));
}

// ---- Leaf awaitables (the only place cancellation is "implemented") ----

// Re-queue the current coroutine (simulates work). Cancellable.
class Yield {
 public:
  explicit Yield(Scheduler& s) : sched_(s) {}
  bool await_ready() const noexcept { return false; }
  template <typename P>
  std::coroutine_handle<> await_suspend(std::coroutine_handle<P> h) {
    token_.emplace(&h.promise());
    if (!token_->RegisterForCancellation([this] { Cancel(); })) {
      return token_->AlreadyCancelled();
    }
    sched_.Schedule(*token_);
    return std::noop_coroutine();
  }
  void await_resume() const noexcept {}

 private:
  void Cancel() {
    // Copy out: Cancelled() destroys the frame that holds *this.
    Scheduler& sched = sched_;
    SuspensionToken token = *token_;
    if (sched.CancelWaiter(token)) token.Cancelled();
  }
  Scheduler& sched_;
  std::optional<SuspensionToken> token_;
};

// Condition variable. Note Wait() takes no token: cancellation is implicit.
class CondVar {
 public:
  explicit CondVar(Scheduler& sched) : sched_(sched) {}

  class Awaiter {
   public:
    explicit Awaiter(CondVar& cv) : cv_(cv) {}
    bool await_ready() const noexcept { return false; }
    template <typename P>
    std::coroutine_handle<> await_suspend(std::coroutine_handle<P> h) {
      token_.emplace(&h.promise());
      if (!token_->RegisterForCancellation([this] { Cancel(); })) {
        return token_->AlreadyCancelled();
      }
      cv_.waiters_.push_back(*token_);
      return std::noop_coroutine();
    }
    void await_resume() const noexcept {}

   private:
    void Cancel() {
      CondVar& cv = cv_;
      SuspensionToken token = *token_;
      // Either still parked here, or NotifyOne already moved it to the ready
      // queue. Pull it back from wherever it is, then destroy.
      if (std::erase(cv.waiters_, token) > 0 || cv.sched_.CancelWaiter(token)) {
        token.Cancelled();
      }
    }
    CondVar& cv_;
    std::optional<SuspensionToken> token_;
  };

  Awaiter Wait() { return Awaiter(*this); }

  void NotifyOne() {
    if (waiters_.empty()) return;
    sched_.Schedule(waiters_.front());
    waiters_.pop_front();
  }

 private:
  Scheduler& sched_;
  std::deque<SuspensionToken> waiters_;
};

// ---- User code: no token anywhere ----

class Channel {
 public:
  explicit Channel(Scheduler& sched) : cv_(sched) {}
  void Push(int v) {
    items_.push_back(v);
    cv_.NotifyOne();
  }
  Co<int> Pop() {
    while (items_.empty()) co_await cv_.Wait();
    int v = items_.front();
    items_.pop_front();
    co_return v;
  }

 private:
  std::deque<int> items_;
  CondVar cv_;
};

Co<void> Consumer(Scheduler& sched, Channel& ch, int id) {
  struct Cleanup {
    int id;
    ~Cleanup() { std::cout << "consumer " << id << " cleanup (RAII)\n"; }
  } cleanup{id};

  for (;;) {  // no exit path: cancellation destroys this frame instead
    int item = co_await ch.Pop();
    std::cout << "consumer " << id << " processes " << item << "\n";
    co_await Yield(sched);
  }
}

Co<void> Producer(Scheduler& sched, Channel& ch) {
  for (int i = 0;; ++i) {
    std::cout << "producer pushes " << i << "\n";
    ch.Push(i);
    co_await Yield(sched);
  }
}

Co<void> StopAfter(Scheduler& sched, std::deque<CoThread*> threads, int ticks) {
  for (int i = 0; i < ticks; ++i) co_await Yield(sched);
  std::cout << "=== cancel requested ===\n";
  for (CoThread* t : threads) t->Cancel();  // callbacks destroy the stacks
}

int main() {
  Scheduler sched;
  Channel ch(sched);

  CoThread c1(ReportExit("consumer 1").handle);
  CoThread c2(ReportExit("consumer 2").handle);
  CoThread prod(ReportExit("producer").handle);
  CoThread stopper(ReportExit("stopper").handle);

  Spawn(sched, c1, Consumer(sched, ch, 1));
  Spawn(sched, c2, Consumer(sched, ch, 2));
  Spawn(sched, prod, Producer(sched, ch));
  Spawn(sched, stopper, StopAfter(sched, {&c1, &c2, &prod}, 3));

  sched.Run();

  std::cout << "live coroutine frames after Run(): " << FrameCounter::live
            << "\n";
  return FrameCounter::live == 0 ? 0 : 1;
}

Sep 12, 2026

C++ template code COMDAT folding

Reference:
Reducing C++ template bloat by factoring out the type-dependent portions of the function


COMDAT folding (also known as Identical Code Folding or ICF/Safe ICF) is a link-time optimization where the linker detects functions or read-only data sections that compile into byte-for-byte identical machine code, merges them into a single instance, and points all call sites to that unified copy.

When instantiates templates over types that share the same underlying memory layout and operations, the compiler often emits redundant assembly:

template <typename T>
void push_item(T* item) {
    // Operations on item...
}

// In translation unit A:
push_item<Dog>(dog_ptr);

// In translation unit B:
push_item<Cat>(cat_ptr);
Because Dog* and Cat* are both raw machine pointers (typically 8 bytes), the generated machine instructions for push_item and push_item are identical. 

Normally, C++ templates emit code into COMDAT sections (Common Data sections) with "link-once" semantics (select any). This allows the linker to discard duplicates of push_item compiled across multiple .cpp files. However, normal deduplication only matches identical symbol names. It cannot eliminate the identical assembly between push_item and push_item because their mangled symbol names differ.

How COMDAT Folding Works

During the link step, the linker inspects all candidate sections:

Content Comparison: The linker compares the byte streams, relocation targets, and alignment requirements of functions marked as foldable (typically COMDAT sections generated by inline functions, template instantiations, and virtual tables).

Section Merging: If two distinct functions (e.g., std::vector<int*>::size() and std::vector<char*>::size()) produce identical instructions and reference identical offsets, the linker discards one function body.

Symbol Redirection: The symbol table entry for the discarded function is updated to point directly to the entry point of the retained function.

Key Benefits

Reduced Binary Footprint: Prevents template-heavy code (like std::vector<T*> for hundreds of pointer types) from inflating executable size.

Instruction Cache (I-Cache) Efficiency: Multiple logically distinct types share hot cache lines instead of thrashing the instruction cache with duplicate code.


The Function Pointer Quirk

Under strict C++ rules, every distinct function must have a unique address:

assert(&push_item<Dog> != &push_item<Cat>);

When COMDAT folding collapses these functions, &push_item<Dog> == &push_item<Cat> evaluates to true. This can break code that relies on function pointer uniqueness for type-tagging or callback registries.

To handle this, linkers provide different safety levels:
LLVM (lld)  --icf=safe Only merges functions whose addresses are never taken, preserving C++ address-uniqueness guarantees.
LLVM (lld)  --icf=all Aggressively merges all identical functions, even if addresses are taken.


Instead of generating redundant machine code for hundreds of pointer instantiations and hoping the linker cleans it up with COMDAT folding / ICF, standard library implementations and runtime systems use type erasure with non-templated (or void-pointer-based) base classes.

By shifting the heavy procedural logic into a shared base class, the exposed template becomes a thin, inline wrapper that carries zero runtime binary overhead.

The Architecture: Base-Derived Split

The pattern divides a container or utility into two layers:

The Erased Base Class: Implements memory allocation, capacity resizing, buffer shifts, and element index arithmetic using void* or raw byte buffers. This code is compiled once into the runtime library or translation unit.

The Typed Template Wrapper: Derives from or wraps the base class. It only exposes strongly typed interfaces, using zero-cost casts (reinterpret_cast or static_cast) to translate between T* and void*.


// --- Shared Implementation (compiled once into binary/lib) ---
class VectorPtrBase {
protected:
    void** data_ = nullptr;
    size_t size_ = 0;
    size_t capacity_ = 0;

    void grow_and_insert(size_t index, void* element) {
        // All heavy buffer reallocation, index shifting,
        // and boundary checks happen HERE once.
        if (size_ == capacity_) {
            size_t new_cap = capacity_ == 0 ? 8 : capacity_ * 2;
            void** new_data = new void*[new_cap];
            for (size_t i = 0; i < size_; ++i) new_data[i] = data_[i];
            delete[] data_;
            data_ = new_data;
            capacity_ = new_cap;
        }
        data_[index] = element;
        ++size_;
    }

    void* get_element(size_t index) const {
        return data_[index];
    }
};

// --- Thin Typed Wrapper (specialization for any pointer type) ---
template <typename T>
class Vector<T*> : private VectorPtrBase {
public:
    void push_back(T* val) {
        // Zero-cost static cast; inlines down to a direct call to the base
        grow_and_insert(size_, static_cast<void*>(val));
    }

    T* operator[](size_t index) const {
        return static_cast<T*>(get_element(index));
    }

    size_t size() const { return size_; }
};

Why This Beats Relying Purely on COMDAT Folding

Faster Compilation Times: The compiler does not have to parse, instantiate, type-check, and generate intermediate representation (IR) / assembly for grow_and_insert across Vector<Apple*>, Vector<Banana*>, and Vector<Car*>.

Lower Linker Overhead: Linker-time ICF requires analyzing section hashes, inspecting instruction bytes, and walking relocation tables to prove equivalence. Pointer erasure eliminates the duplicate sections before the object files reach the linker.

Guaranteed Code Sharing: COMDAT folding is sensitive to subtle differences (such as debug information emission, compiler optimization levels, or platform-specific pointer calling conventions). The base-class approach enforces code sharing by construction.

Preserved Pointer Address Guarantees: Because the wrapper's member functions inline entirely into the caller or delegate to the shared base, it avoids issues where --icf=safe refuses to fold functions whose addresses were taken.

Sep 11, 2026

[left-right datastructure] The Cost of Concurrency Coordination

I used to use this dual-copy/pointer swap trick for Linkedin's ATS server.

Reference:
The Cost of Concurrency Coordination with Jon Gjengset
[low latency] What is low latency (definition)

In concurrent systems programming, conventional wisdom often reduces synchronization performance to simple rules of thumb:

  • "Mutexes are slow because threads get descheduled."
  • "If your workload is read-heavy, swap out your Mutex for a Reader-Writer Lock (RwLock)."
  • "Lock-free data structures are inherently fast."
Experience engineer should know these statements aren't true.

It really based on the workload patterns. (DoD)

The RwLock Trap

When developers see read contention on a mutex, the standard instinct is reaching for a Reader-Writer Lock (std::sync::RwLock in Rust, std::shared_mutex in C++). In theory, multiple readers are non-exclusive and should execute cleanly in parallel.

In practice, the benchmark reveals something surprising:
The RwLock read throughput starts roughly equal to the Mutex.
As the number of concurrent reader threads grows, RwLock performance degrades faster and ends up significantly worse than the basic Mutex.


The Hardware Reality: Cache Lines and the MESI Protocol


Why RwLock::read() is Actually a Write

Here lies the catch: Taking a read lock is not a read operation.

To track how many active readers hold the lock, an RwLock maintains an internal reader counter. When a reader calls read(), the CPU must execute an atomic increment (fetch_add) on that shared counter.

Core 0 (Reader 1)   --> fetch_add(reader_count) --> Needs Exclusive Ownership (Line in 'M')
Core 1 (Reader 2)   --> fetch_add(reader_count) --> Forces Core 0 invalidation; pulls line to Core 1
Core 0 (Releasing)  --> fetch_sub(reader_count) --> Pulls line back from Core 1

Every single acquire and release triggers cache-line bouncing across the processor interconnect. Each transition costs ~30 ns. Across acquire and release, a thread spends ~60 ns just synchronizing the lock state—over half the latency of a trip out to main RAM.




Why does Mutex hold up better under extreme thread contention than RwLock?

With a Mutex, only the current owner touches the lock line. Other threads block or queue up in sequence.
With an RwLock, dozens of reader threads aggressively hammer the exact same counter simultaneously, creating intense cache-line ping-pong across every core.


The Left-Right Data Structure: Coordination Without Contention

To make readers truly scalable, readers must never write to a shared cache line.

Jon presents Left-Right, a concurrency primitive, designed for workloads with frequent reads and infrequent writes (e.g., in-memory key-value lookups, routing tables, configuration maps).

High-Level Architecture

Instead of locking access to a single instance, Left-Right maintains two identical copies of the underlying data structure (the Left copy and the Right copy), mediated by an atomic pointer.



The Read Path (Wait-Free & Shared-State Free)

Every reader thread is registered with a private, thread-local counter aligned to its own cache line.
When reading:
  • The reader announces its entry by updating its own thread-local counter.
  • It loads the global atomic pointer to find the current active copy (Left or Right).
  • It executes the read directly on that copy without taking any locks.
  • It signals completion on its private counter.
  • Because each reader modifies only its own cache line, there is zero cross-core invalidation between readers. Their cache lines stay in the Exclusive/Modified state within their local L1/L2 caches.

The Write Path (Two-Phase Reconciliation)

  • Step 1: Writer mutates Right Copy (inactive)
  • Step 2: Writer swaps Atomic Pointer to Right
  • Step 3: Writer waits for readers in Left Copy to exit (epochs/counters)
  • Step 4: Writer replays mutations onto Left Copy
Mutate Inactive Copy: The writer applies the update to the copy that readers aren't currently directed to (e.g., the Right copy).
Atomic Pointer Swap: The writer atomically swings the pointer to Right. All new incoming read operations will now read from Right.
Wait for Old Readers: Readers that entered before the pointer swap are still safely executing inside the Left copy. The writer scans the per-thread counters in a loop until it confirms that all readers active during the switch have finished.
Replay & Synchronize: Once the Left copy is completely drained of readers, the writer replays the exact same update from an operational log onto the Left copy. Both copies are now identical again.

The "Four-Core Drop": A Real-World Lesson in False Sharing

While benchmarking Left-Right, Jon observed expected linear scalability up to three cores—then suddenly, at four cores, throughput plummeted by nearly an order of magnitude:

Throughput
    ^
    |         /
    |       /
    |     /   <-- Expected linear scaling
    |   /
    |  *
    |       |     \__ * <-- Plummeted 10x at 4 cores!
    +----------------------------------------> Cores

The bug wasn't an algorithmic flaw or a NUMA boundary traversal. It was False Sharing:
  • The internal implementation stored per-thread reader counters together in an array.
  • Multiple 64-bit counter values fit inside a single 64-byte cache line (8 bytes × 8 = 64 bytes).
  • Even though Core 0 and Core 1 were updating completely independent counter variables, those variables shared the exact same physical cache line. The CPU was forced to ping-pong the line between cores on every single reader check-in.

The Fix

Enforce cache-line alignment on the counter type:

#[repr(align(64))]
struct AlignedReaderCounter {
    counter: AtomicUsize,
}

By ensuring each thread's counter lived on its own dedicated 64-byte boundary, the false sharing vanished, and performance restored to ~3 billion reads/second across 10 cores—scaling linearly.

Engineering Trade-offs: When Should You Use Left-Right?

Left-Right is not a magic drop-in replacement for every concurrency scenario. It trades memory and write performance for extreme read throughput:

ConstraintLeft-Right Trade-Off
Memory FootprintDoubled (2×), because two full copies of the data structure must live in memory.
Write OverheadHigh. Writers must apply changes twice (once per copy), keep an operation log, and wait for reader epochs to drain.
Write ConcurrencySingle writer only. Multiple concurrent writers require an external lock.
Consistency ModelEventually consistent / Non-linearizable. Readers might see slightly stale data before a pointer swap, and writers cannot immediately read-your-own-writes from the reader handle.
DeterminismOperations must be completely deterministic so that replaying them on the second copy yields identical internal state.


Summary Takeaways

  • "Lock-Free" does not mean "Contention-Free": Eliminating OS-level locks doesn't matter if your threads are repeatedly modifying the same atomic variable on a single shared cache line.
  • Short critical sections expose synchronization overhead: If your protected work takes 5 ns (like a hash map lookup) and your lock acquire/release costs 60 ns in cache line bounces, synchronization dominates your runtime.
  • Align for the hardware: Always guard against false sharing in concurrent per-thread arrays using 64-byte alignment (alignas(64) in C++, #[repr(align(64))] in Rust).
  • Tailor algorithms to your access patterns: When your system is 99% reads and you can afford the memory overhead and deterministic write logs, patterns like Left-Right turn cache lines from a bottleneck into an advantage.