proomt

Search

Search posts, papers, and topics

All posts

Raymond Chen2 min readintermediate

std::call_once vs. std::async

Summary

Raymond Chen compares using std::call_once versus std::async (deferred) for lazy initialization in C++. He shows that std::async can be wrapped in a shared_future for repeatable get() calls, but it adds heap allocation and extra code, while call_once is tiny; exception behavior also differs.

  • Wrap a deferred std::async in a shared_future to allow multiple get() calls and cache the result.
  • shared_future::get() is const and thread‑safe, returning a const reference to the cached value.
  • std::call_once compiles to a pointer‑sized object, while std::future incurs heap allocation and pulls in thread library code.
  • Exception safety differs: some std::call_once implementations are not exception‑safe, unlike std::async’s handling.

C++ engineers implementing thread‑safe lazy initialization need to understand the performance and safety trade‑offs between call_once and async.

6/10

Related reading

  1. Magic statics vs. std::call_once

    Function‑local "magic" statics give you thread‑safe, one‑time init for static data, but they’re limited to static storage and shared across all instances. Use `std::call_once` (or a small `lazy<T>` wrapper) when you need per‑object lazy init or when the value isn’t a static. The post shows concrete code for both approaches, explains the pitfalls of using a static inside a member function, and ske…

    Raymond Chenmicrosoft.com3 min
  2. Textbook review: Is Parallel Programming Hard, And, If So, What Can You Do About It?

    A detailed, personal review of Paul McKenney’s free online textbook on parallel programming. The author, coming from a TLA⁺/distributed‑systems background, finds the early chapters excellent for building intuition about CPU caches, memory ordering, and false‑sharing, but notes gaps (e.g., shallow coverage of C++11 atomics and MESI). The review is concrete, cites specific chapters, and offers prac…

    Lobstersahelwer.ca8 minlobste.rs32
  3. Kodebits Day 95: Lazy Sequences [FREE]

    This short Kotlin challenge demonstrates lazy sequences. It shows how `asSequence()` combined with `map`, `filter`, and `take` processes elements one at a time, evaluating lazily only when a terminal operation is called.

    Ray Wenderlichkodeco.com1 min
  4. Article: Your Next DSL Author Is a Language Model

    Typed Domain Grounding (TDG) embeds a DSL inside a mainstream language the LLM already knows (e.g., Kotlin) and uses the host compiler as an oracle. The author describes five building blocks—embedding, choosing a host language with high training‑data frequency, compiler‑driven type safety, a generate‑compile‑repair loop, and an on‑demand teaching tool—and shows measured results from kUML, a Kotli…

    InfoQinfoq.com18 min