liveBook · Manning

Resource acquisition is initialization

As explained in C++ Concurrency in Action, Second Edition

Resource Acquisition Is Initialization is a C++ programming idiom that binds resource ownership and release to object lifetime.

RAII ties a resource’s cleanup to an object’s lifetime. A guard’s destructor releases the resource when its scope ends, including when an exception interrupts normal execution. section 2.1.3 section 3.2.1

Listing 2.3. Using RAII to wait for a thread to complete
class thread_guard
{
    std::thread& t;
public:
    explicit thread_guard(std::thread& t_):
        t(t_)
    {}
    ~thread_guard()
    {
        if(t.joinable())
        {
            t.join();
        }
    }
    thread_guard(thread_guard const&)=delete;
    thread_guard& operator=(thread_guard const&)=delete;
};
struct func;          #1
void f()
{
    int some_local_state=0;
    func my_func(some_local_state);
    std::thread t(my_func);
    thread_guard g(t);
    do_something_in_current_thread();
}

A thread_guard joins its thread in the destructor; scope-based destruction also runs when the function exits by exception. section 2.1.3

For mutexes, std::lock_guard locks on construction and unlocks on destruction, avoiding manual unlocks on every exit path. section 3.2.1

How C++ Concurrency in Action, Second Edition covers it

How deep it goes
Works through destructor behavior with thread and mutex examples, including cleanup during exceptions.
Examples
Demonstrates a thread_guard that joins a thread and std::lock_guard protecting a shared list.
What you can do after
Apply it via std::lock_guard or a thread guard to release mutexes or join threads on normal and exceptional exits.
How it connects
Connects object lifetime and destructors to exceptions, mutexes, and std::thread.

Also explained in

Compare how 4 books explain resource acquisition is initialization →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of C++ Concurrency in Action, Second Edition. The section links point to the parts of the book it draws on.