liveBook · Manning

Ownership transfer

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

Ownership transfer is the reassignment of responsibility for managing a resource, such as a lock, from one entity to another.

Ownership transfer moves responsibility for a resource between objects without copying it. In C++, movable, noncopyable types such as `std::thread` and `std::unique_lock` use this pattern. Moving from a named object requires `std::move`; a temporary can be moved from implicitly. section 2.3 section 3.2.7

void some_function();
void some_other_function();
std::thread t1(some_function);
std::thread t2=std::move(t1);
t1=std::thread(some_other_function);
std::thread t3;
t3=std::move(t2);
t1=std::move(t3);          #1

The sequence moves thread ownership among three objects. After a move, the source no longer owns that thread; assigning into an object that already owns a thread calls `std::terminate()`. section 2.3

A function can return a `std::unique_lock` to let its caller continue working under the same lock. Returning the local lock transfers ownership automatically; the caller can then rely on the protected data remaining unchanged by other threads while the lock is held. section 3.2.7

std::unique_lock<std::mutex> get_lock()
{
    extern std::mutex some_mutex;
    std::unique_lock<std::mutex> lk(some_mutex);
    prepare_data();
    return lk;                                      #1
}
void process_data()
{
    std::unique_lock<std::mutex> lk(get_lock());    #2
    do_something();
}


!@%STYLE%@!
{"css":"{\"css\": \"font-weight: bold;\"}","target":"[[{\"line\":5,\"ch\":52},{\"line\":5,\"ch\":54}],[{\"line\":9,\"ch\":52},{\"line\":9,\"ch\":54}]]"}
!@%STYLE%@!

Here, `get_lock()` acquires the mutex and prepares data before returning its lock. `process_data()` receives the lock and performs further work while retaining protection. section 3.2.7

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

How deep it goes
Walks through thread and lock transfers, including implicit moves and a thread-assignment termination pitfall, without detailing move internals.
Examples
Uses thread transfers among three objects and a function that returns a lock for continued protected work.
What it assumes
Explains lvalue-versus-rvalue transfer rules while directing deeper move-semantics background elsewhere.
What you can do after
Apply `std::move` to transfer from named owners and avoid assigning over an associated `std::thread`.
How it connects
Connects move semantics with `std::thread`, `std::unique_lock`, mutexes, and protected data.

Also explained in

Compare how 3 books explain ownership transfer →

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.