Mastering the C++17 STL: Make full use of the standard library components in C++17 by O'Dwyer Arthur

Mastering the C++17 STL: Make full use of the standard library components in C++17 by O'Dwyer Arthur

Author:O'Dwyer, Arthur [O'Dwyer, Arthur]
Language: eng
Format: azw3, epub
Tags: COM051220 - COMPUTERS / Programming / Parallel, COM051390 - COMPUTERS / Programming / Open Source, COM051070 - COMPUTERS / Programming Languages / C++
Publisher: Packt Publishing
Published: 2017-09-28T04:00:00+00:00


std::thread thread_b([&]() {

prep_work();

ready_p.set_value();

main_work();

});

// Wait for thread B to be ready.

ready_f.wait();

// Now thread B has completed its prep work.

Compare this version to the code samples from the section titled "Waiting for a condition." This version is much cleaner! There's practically no cruft, no boilerplate at all. The "signal B's readiness" and "wait for B's readiness" operations both take only a single line of code. So this is definitely the preferred way to signal between a single pair of threads, as far as syntactic cleanliness is concerned. For yet a fourth way to signal from one thread to a group of threads, see this chapter's subsection titled "Identifying individual threads and the current thread."

There is a price to pay for std::future, though. The price is dynamic memory allocation. You see, promise and future both need access to a shared storage location, so that when you store 42 in the promise side, you'll be able to pull it out from the future side. (That shared storage location also holds the mutex and condition variable required for synchronizing between the threads. The mutex and condition variable haven't disappeared from our code; they've just moved down a layer of abstraction so that we don't have to worry about them.) So, promise and future both act as a sort of "handle" to this shared state; but they're both movable types, so neither of them can actually hold the shared state as a member. They need to allocate the shared state on the heap, and hold pointers to it; and since the shared state isn't supposed to be freed until both handles are destroyed, we're talking about shared ownership via something like shared_ptr (see Chapter 6, Smart Pointers). Schematically, promise and future look like this:



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.