Thread Lifecycle and RAII
In the previous chapter we looked at the low-level mechanics of the CPU cache and OS threads, and now we can finally write our first multithreaded program. But before typing std::thread t(...), we need to get one thing straight: a thread is a resource. It occupies OS kernel objects, stack space, TLS storage, and more. Just like file handles and dynamic memory, a thread must be properly acquired and released — otherwise what awaits you is std::terminate and resource leaks.
In this chapter we start with the basic usage of std::thread, work our way through the pitfalls of passing arguments and the semantics of ownership transfer, and finally wrap all that complexity up with RAII. The goal is for multithreaded code to have the same clear ownership and deterministic resource release as single-threaded code.