Build a value exactly once and report how many later reads were served from cache.

Call Once Coordination Report

call_once_coordination_report.cpp
#include <iostream>
#include <mutex>
#include <string>

int main() {
    int reads = ;
    std::once_flag built;
    int value = 0;
    int builds = 0;
    int served = 0;

    for (int i = 0; i < reads; ++i) {
        std::call_once(built, [&]() {
            value = 42;
            builds += 1;
        });
        served += 1;
    }

    int cached = (builds > 0) ? value : 0;

    std::string status;
    if (served == 0) {
        status = "unset";
    } else if (served > builds) {
        status = "cached";
    } else {
        status = "set";
    }

    std::cout << "reads=" << reads
              << " served=" << served
              << " builds=" << builds
              << " value=" << cached
              << " " << status << std::endl;
    return 0;
}
#include <iostream>
#include <mutex>
#include <string>

int main() {
    int reads = ;
    std::once_flag built;
    int value = 0;
    int builds = 0;
    int served = 0;

    for (int i = 0; i < reads; ++i) {
        std::call_once(built, [&]() {
            value = 42;
            builds += 1;
        });
        served += 1;
    }

    int cached = (builds > 0) ? value : 0;

    std::string status;
    if (served == 0) {
        status = "unset";
    } else if (served > builds) {
        status = "cached";
    } else {
        status = "set";
    }

    std::cout << "reads=" << reads
              << " served=" << served
              << " builds=" << builds
              << " value=" << cached
              << " " << status << std::endl;
    return 0;
}
#include <iostream>
#include <mutex>
#include <string>

int main() {
    int reads = ;
    std::once_flag built;
    int value = 0;
    int builds = 0;
    int served = 0;

    for (int i = 0; i < reads; ++i) {
        std::call_once(built, [&]() {
            value = 42;
            builds += 1;
        });
        served += 1;
    }

    int cached = (builds > 0) ? value : 0;

    std::string status;
    if (served == 0) {
        status = "unset";
    } else if (served > builds) {
        status = "cached";
    } else {
        status = "set";
    }

    std::cout << "reads=" << reads
              << " served=" << served
              << " builds=" << builds
              << " value=" << cached
              << " " << status << std::endl;
    return 0;
}
run-once initialization A write-once value is built by the first reader and shared by the rest. A `std::once_flag` paired with `std::call_once` runs its initializer the first time it is reached and skips it on every later call, so the build counter rises to one no matter how many reads occur. Each read is served whether or not it triggered the build, so the report compares served reads against builds and labels the value unset when never read, set when built on its only read, or cached when later reads reused the single build.