We will analyse such code
#include
#include
#include
void promise_future_approach() {
std::promise promise;
std::future future = promise.get_future();
auto function = [](std::promise promise) {
// ...
promise.set_value(10);
};
std::thread t(function, std::move(promise));
std::cout << future.get() << std::endl;
t.join();
}
void async_approach() {
auto function = []() {
// ...
return 20;
};
std::future future = std::async(function);
std::cout << future.get() << std::endl;
}
int main() {
promise_future_approach();
async_approach();
return 0;
}
// example from https://infotraining.bitbucket.io/cpp-thd/async_future.html
#include
#include
#include
#include
int main() {
std::future future = std::async(std::launch::async, []() {
std::this_thread::sleep_for(std::chrono::seconds(3));
return 8;
});
std::cout << "waiting...\n";
std::future_status status;
do {
status = future.wait_for(std::chrono::seconds(1));
if (status == std::future_status::deferred) {
std::cout << "deferred\n";
} else if (status == std::future_status::timeout) {
std::cout << "timeout\n";
} else if (status == std::future_status::ready) {
std::cout << "ready!\n";
}
} while (status != std::future_status::ready);
std::cout << "result is " << future.get() << '\n';
return 0;
}
Your abilities after Multithreading – Asynchronous tasks training
-
know about problems with the usage of
std::threads
- use future and promise for communication between asynchronous tasks or threads
- use async to run tasks asynchronously
-
know and apply best practices of
future
,promise
,async
andpackaged_task
Agenda
- problems with threads
-
future
andpromise
-
packaged_task
-
async
- recap
Activities
- pre-work to be done before our training
- pre-test pre-test at the beginning
- exercises followed by trainers implementation
- coding dojo
- participants solutions code review
- post-work with code review
- post-test one week after the training
- certificate of completion
Duration
- 1 day (7 hours with breaks)
Form
- online
- classroom
Order Multithreading – Asynchronous tasks training
Related trainings
Multithreading - atomic, conditional_variable, call_once
Other utilities from thread support library that are used in threads or asynchronous tasks