Skip to content

Last updated:2026-10-13


comments: true keywords: C++ Concurrency in Action examples,std::thread ownership,join detach,thread safety description: "Guided reading of the project's C++ Concurrency in Action examples: thread creation, join, ownership transfer, hardware concurrency, and pitfalls to check before running." title: C++ Concurrency in Action: Chapter 1–2 Code Guide | C++那些事


C++ Concurrency in Action: guide to the code

This page is a guide to the project's chapter 1 and 2 example files, not a reproduction of the book. Work through the examples in order and keep three questions in view: Who owns the thread? How does it finish? Can it outlive data it references?

Reading order

File What to inspect
Chapter 1: 1_helloworld.cpp std::thread starts work; join() waits for it. A joinable thread must be joined or detached before its destructor runs.
Chapter 2: 2.1_basic.cpp A callable can hold a reference to local state. Check every exit path before allowing a thread to continue.
Chapter 2: 2.2_transfer.cpp Observe std::move when transferring a unique_ptr to a thread. Do not run this file unchanged: its std::thread objects are not joined or detached before main ends, so destruction of a joinable thread calls std::terminate.
Chapter 2: 2.3_ownership.cpp Compare movable, noncopyable thread ownership with a scope guard that joins in its destructor.
Chapter 2: 2.4_runtime.cpp Examine how the parallel accumulate example limits the number of worker threads; hardware_concurrency() is only a hint and may return zero.
Chapter 2: 2_5_id.cpp Compare the main thread's ID with std::this_thread::get_id() in a worker.

Run a safe first example

From the repository root, compile the chapter 1 file with a C++11 or newer compiler and thread support:

c++ -std=c++17 -pthread concurrency/concurrency_v1/chapter1/1_helloworld.cpp -o hello-thread
./hello-thread

Expected output is hello world. For 2.2_transfer.cpp, add t.join(); tt.join(); before leaving main if you are experimenting with that file, and ensure referenced objects remain alive until joining. Do not assume detach() is a general substitute: detached work can outlive local variables.

Continue on this site

After these examples, study threading in C++, RAII, and smart pointers as parameters. The external Chinese notes for the second edition are supplementary and may be temporarily unavailable.