SlideShare a Scribd company logo
1 of 26
Futures
Introduction 
Motivation 
Asynchronous Return Object: 
• future<T> 
Asynchronous Provider Objects: 
• async<F, Args…> 
• packaged_task<R, Args…> 
• promise<T> 
Continuation passing style 
Q&A
[C++03, 1.9.6] 
• The observable behavior of the abstract machine is 
its sequence of reads and writes to volatile data and 
calls to library I/O functions. 
 [C++11, 1.10.1]: 
• A thread of execution (also known as a thread) is a 
single flow of control within a program... The 
execution of the entire program consists of an 
execution of all of its threads...
 [C++11, 30.1.1]: 
• The following subclauses describe components 
to create and manage threads (1.10), perform 
mutual exclusion, and communicate 
conditions and values between threads… 
Subclause Header 
Threads <thread> 
Mutual exclusion <mutex> 
Condition variables <condition_variable> 
Futures <future>
Having independent time consuming tasks: 
// ... 
device target_device; 
target_device.initialize(); // <- time consuming 
configuration_storage db; 
configuration config; 
db.load(config); // <- time consuming 
target_device.configure(config);
Execute time consuming tasks 
simultaneously, naive approach: 
// ... 
configuration_storage db; 
configuration config; 
thread loader([&db, &config]{ db.load(config); }); 
// <- run loading config in a separate thread 
device target_device; 
target_device.initialize(); 
// <- continue device initialization in current thread 
loader.join(); 
// <- assume loading done at this point 
target_device.configure(config);
Execute time consuming tasks 
simultaneously, thread pool approach: 
class async_exec_service { 
public: 
void exec(function<void()> f); 
}; 
// ... 
async_exec_service exec_service; 
// ... 
configuration_storage db; 
configuration config; 
exec_service.exec([&db, &config]{ db.load(config); }); 
// <- run loading config in the thread pool 
device target_device; 
target_device.initialize(); 
// <- continue device initialization in current thread 
// hmmm... are we ready for proceed ??? 
target_device.configure(config);
 Execute time consuming tasks simultaneously, thread 
pool approach with synchronization: 
class async_exec_service { public: void exec(function<void()> f); }; 
// ... 
async_exec_service exec_service; 
// ... 
configuration_storage db; 
unique_ptr<configuration> config; 
mutex config_guard; 
condition_variable config_cv; 
exec_service.exec([&]{ 
unique_lock<mutex> lock(config_guard); 
config.reset(new configuration); 
db.load(*config); 
config_cv.notify_one(); 
}); // <- run loading config in the thread pool 
device target_device; 
target_device.initialize(); // continue device initialization in current thread 
{ // wait for configuration loading done 
unique_lock<mutex> lock(config_guard); 
config_cv.wait(lock, [&]{ return (config != nullptr); }); 
} 
// we are ready for proceed 
target_device.configure(*config);
The Standard Library provides a unified 
solution communicate data between 
threads: 
• shared state object – privately held object with a 
placeholder for result and some auxiliary data; 
• asynchronous return object – reads result from 
a shared state; 
• asynchronous provider - provides shared state 
object with a value.
SharedState – internal shared state; 
future – asynchronous return object; 
Setter – asynchronous provider object: 
• async 
• packaged_task 
• promise
 Execute time consuming tasks simultaneously, using 
future<T>: 
class async_exec_service { 
public: 
template <typename _Function> 
auto exec(_Function&& f) -> future<decltype(f())> 
{ /*...*/ } 
}; 
async_exec_service exec_service; 
// ... 
configuration_storage db; 
future<configuration> config = exec_service.exec([&db]{ 
configuration config; 
db.load(config); 
return config; 
}); 
device target_device; 
target_device.initialize(); 
target_device.configure(config.get()); 
// wait for result and proceed
valid() – tests if the future has a shared 
state; 
get() – retrieves value, wait if needed; 
wait()/wait_for(delay)/wait_until(time) – 
waits the future to be populated with result; 
share() – makes shared_future from this 
future; invalidates this future object.
shares its shared state object between 
several asynchronous return objects: 
the main purpose – signal the result is 
ready to multiple waiting threads
Runs a function in a separate thread and 
set its result to future: 
• step back to naive approach: 
configuration_storage db; 
future<configuration> config = async([&db]{ 
configuration config; 
db.load(config); 
return config; 
}); // run loading config in a separate thread 
device target_device; 
target_device.initialize(); 
// continue device initialization in current thread 
target_device.configure(config.get());
template< class Function, class... Args> 
result_type async(Function&& f, Args&&... args); 
template< class Function, class... Args > 
result_type async(launch policy, Function&& f, Args&&... args); 
async launch policy: 
 launch::async – launch a new thread for execution; 
 launch::deferred – defers the execution until the 
returned future value accessed; performs execution in 
current thread; 
 launch::async|launch::deferred – used by default, 
allows the implementation to choose one.
configuration_storage db; 
future<configuration> config = async([&db]{ 
configuration config; 
db.load(config); 
return config; 
}); // run loading config in a separate thread 
device target_device; 
if (!target_device.initialize()) { 
return; // what will happen to config here ??? 
} 
target_device.configure(config.get()); 
 [3.6.8/5]: 
• … If the implementation chooses the launch::async policy, 
- a call to a waiting function on an asynchronous return object that shares 
the shared state created by this async call shall block until the 
associated thread has completed, as if joined; 
…
 provides better control over execution; 
 does not execute threads itself; 
 provides a wrapper on a function or a callable object for 
store returned value/exception in a future. 
configuration_storage db; 
packaged_task<configuration ()> load_config([&db] { 
configuration config; 
db.load(config); 
return config; 
}); 
future<configuration> config = load_config.get_future(); 
// just get future<> for future :) 
load_config(); // loading config goes here 
device target_device; 
target_device.initialize(); 
target_device.configure(config.get());
 Implementation for async_exec_service: 
class async_exec_service { 
queue<function<void ()>> _exec_queue; 
// worker threads will take functions from _exec_queue 
// ... 
void enqueue(function<void ()> task) {/* put task to _exec_queue */} 
public: 
template <typename _Function> 
auto exec(_Function&& f) -> future<decltype(f())> 
{ 
typedef decltype(f()) _Result; 
shared_ptr<packaged_task<_Result()>> task = 
make_shared<packaged_task<_Result()>>(f); 
function<void()> task_wrapper = [task]{(*task)();}; 
enqueue(task_wrapper); 
return task->get_future(); 
} 
// ... 
};
 provides the highest level of control over the shared 
state; 
 does not require a function or callable object for populate 
shared state; 
 requires executing thread explicitly set value/exception to 
shared state.
 Yet another implementation for async_exec_service: 
class async_exec_service { 
queue<function<void ()>> _exec_queue; 
// worker threads will take functions from _exec_queue 
// ... 
void enqueue(function<void ()> task) {/* put task to _exec_queue */} 
public: 
template <typename _Function> 
auto exec(_Function&& f) -> future<decltype(f())> 
{ 
typedef decltype(f()) _Result; 
shared_ptr<promise<_Result>> result = 
make_shared<promise<_Result>>(); 
function<void()> task_wrapper = [result, f]{ 
try { 
result->set_value(f()); 
} catch (...) { 
result->set_exception(current_exception()); 
} 
} 
enqueue(task_wrapper); 
return result->get_future(); 
} 
};
. || …
Currently is not a part of C++ Standard 
Going to be included in C++17 (N3857) 
Already available in boost
 compose two futures by declaring one to be the 
continuation of another: 
device target_device; 
configuration_storage db; 
future<void> configure = async([&db]{ 
configuration config; 
db.load(config); 
return config; 
}).then([&target_device](future<configuration> config){ 
// JUST FOR EXAMPLE: 
// config is ready at this point, 
// but it doesn’t mean we could already configure the device 
}); 
target_device.initialize();
 wait a number of futures for at least one to be 
ready: 
device target_device; 
configuration_storage db; 
configuration config; 
future<bool> tasks[] = { 
async([&target_device]{ return target_device.initialize(); }), 
async([&db, &config]{ db.load(config); return true; }), 
}; 
future<vector<future<bool>>> anyone = when_any(begin(tasks), end(tasks)); 
future<bool> anyone_completed = anyone.then( 
[](future<vector<future<bool>>> lst) { 
// JUST FOR EXAMPLE 
for (future<bool>& f: lst) { 
if (f.is_ready()) 
return f.get(); // won't block here 
} 
});
 wait for a number of futures to be ready: 
device target_device; 
configuration_storage db; 
future<bool> init_device = async([&target_device]{ 
return target_device.initialize(); 
}); 
future<configuration> load_config = async([&db]{ 
configuration config; 
db.load(config); 
return config; 
}); 
future<tuple<future<bool>, future<configuration>>> init_all = 
when_all(init_device, load_config); 
future<bool> device_ready = init_all.then( 
[&target_device](tuple<future<bool>, future<configuration>> params){ 
bool hw_ok = get<0>().get(); 
if (!hw_ok) return false; 
configuration config = get<1>().get(); 
target_device.configure(config); 
return true; 
} 
);
Thank You!

More Related Content

What's hot

JDK1.7 features
JDK1.7 featuresJDK1.7 features
JDK1.7 featuresindia_mani
 
C++aptitude questions and answers
C++aptitude questions and answersC++aptitude questions and answers
C++aptitude questions and answerssheibansari
 
classes & objects in cpp overview
classes & objects in cpp overviewclasses & objects in cpp overview
classes & objects in cpp overviewgourav kottawar
 
Finagle and Java Service Framework at Pinterest
Finagle and Java Service Framework at PinterestFinagle and Java Service Framework at Pinterest
Finagle and Java Service Framework at PinterestPavan Chitumalla
 
DRYing to Monad in Java8
DRYing to Monad in Java8DRYing to Monad in Java8
DRYing to Monad in Java8Dhaval Dalal
 
data Structure Lecture 1
data Structure Lecture 1data Structure Lecture 1
data Structure Lecture 1Teksify
 
Node.js behind: V8 and its optimizations
Node.js behind: V8 and its optimizationsNode.js behind: V8 and its optimizations
Node.js behind: V8 and its optimizationsDawid Rusnak
 
Advanced Java Practical File
Advanced Java Practical FileAdvanced Java Practical File
Advanced Java Practical FileSoumya Behera
 
Александр Гранин, Функциональная 'Жизнь': параллельные клеточные автоматы и к...
Александр Гранин, Функциональная 'Жизнь': параллельные клеточные автоматы и к...Александр Гранин, Функциональная 'Жизнь': параллельные клеточные автоматы и к...
Александр Гранин, Функциональная 'Жизнь': параллельные клеточные автоматы и к...Sergey Platonov
 
Declarative Internal DSLs in Lua: A Game Changing Experience
Declarative Internal DSLs in Lua: A Game Changing ExperienceDeclarative Internal DSLs in Lua: A Game Changing Experience
Declarative Internal DSLs in Lua: A Game Changing ExperienceAlexander Gladysh
 
Uncommon Design Patterns
Uncommon Design PatternsUncommon Design Patterns
Uncommon Design PatternsStefano Fago
 
12. stl örnekler
12.  stl örnekler12.  stl örnekler
12. stl örneklerkarmuhtam
 
Java_practical_handbook
Java_practical_handbookJava_practical_handbook
Java_practical_handbookManusha Dilan
 
Concurrency Concepts in Java
Concurrency Concepts in JavaConcurrency Concepts in Java
Concurrency Concepts in JavaDoug Hawkins
 

What's hot (20)

JDK1.7 features
JDK1.7 featuresJDK1.7 features
JDK1.7 features
 
srgoc
srgocsrgoc
srgoc
 
C++aptitude questions and answers
C++aptitude questions and answersC++aptitude questions and answers
C++aptitude questions and answers
 
classes & objects in cpp overview
classes & objects in cpp overviewclasses & objects in cpp overview
classes & objects in cpp overview
 
Link list
Link listLink list
Link list
 
Finagle and Java Service Framework at Pinterest
Finagle and Java Service Framework at PinterestFinagle and Java Service Framework at Pinterest
Finagle and Java Service Framework at Pinterest
 
DRYing to Monad in Java8
DRYing to Monad in Java8DRYing to Monad in Java8
DRYing to Monad in Java8
 
data Structure Lecture 1
data Structure Lecture 1data Structure Lecture 1
data Structure Lecture 1
 
Node.js behind: V8 and its optimizations
Node.js behind: V8 and its optimizationsNode.js behind: V8 and its optimizations
Node.js behind: V8 and its optimizations
 
Advanced Java Practical File
Advanced Java Practical FileAdvanced Java Practical File
Advanced Java Practical File
 
A Taste of Dotty
A Taste of DottyA Taste of Dotty
A Taste of Dotty
 
Александр Гранин, Функциональная 'Жизнь': параллельные клеточные автоматы и к...
Александр Гранин, Функциональная 'Жизнь': параллельные клеточные автоматы и к...Александр Гранин, Функциональная 'Жизнь': параллельные клеточные автоматы и к...
Александр Гранин, Функциональная 'Жизнь': параллельные клеточные автоматы и к...
 
Thread
ThreadThread
Thread
 
iOS Session-2
iOS Session-2iOS Session-2
iOS Session-2
 
Declarative Internal DSLs in Lua: A Game Changing Experience
Declarative Internal DSLs in Lua: A Game Changing ExperienceDeclarative Internal DSLs in Lua: A Game Changing Experience
Declarative Internal DSLs in Lua: A Game Changing Experience
 
Uncommon Design Patterns
Uncommon Design PatternsUncommon Design Patterns
Uncommon Design Patterns
 
12. stl örnekler
12.  stl örnekler12.  stl örnekler
12. stl örnekler
 
Java_practical_handbook
Java_practical_handbookJava_practical_handbook
Java_practical_handbook
 
Concurrency Concepts in Java
Concurrency Concepts in JavaConcurrency Concepts in Java
Concurrency Concepts in Java
 
Java 8 Workshop
Java 8 WorkshopJava 8 Workshop
Java 8 Workshop
 

Similar to C++11 Multithreading - Futures

Grand Central Dispatch
Grand Central DispatchGrand Central Dispatch
Grand Central Dispatchcqtt191
 
Gr8conf EU 2018 - Bring you infrastructure under control with Infrastructor
Gr8conf EU 2018 - Bring you infrastructure under control with InfrastructorGr8conf EU 2018 - Bring you infrastructure under control with Infrastructor
Gr8conf EU 2018 - Bring you infrastructure under control with InfrastructorStanislav Tiurikov
 
Java util concurrent
Java util concurrentJava util concurrent
Java util concurrentRoger Xia
 
OOPS USING C++(UNIT 2)
OOPS USING C++(UNIT 2)OOPS USING C++(UNIT 2)
OOPS USING C++(UNIT 2)SURBHI SAROHA
 
Back to the future with C++ and Seastar
Back to the future with C++ and SeastarBack to the future with C++ and Seastar
Back to the future with C++ and SeastarTzach Livyatan
 
Avoiding callback hell in Node js using promises
Avoiding callback hell in Node js using promisesAvoiding callback hell in Node js using promises
Avoiding callback hell in Node js using promisesAnkit Agarwal
 
Using c++Im also using a the ide editor called CodeLiteThe hea.pdf
Using c++Im also using a the ide editor called CodeLiteThe hea.pdfUsing c++Im also using a the ide editor called CodeLiteThe hea.pdf
Using c++Im also using a the ide editor called CodeLiteThe hea.pdffashiongallery1
 
Scheduling tasks the human way - Brad Wood - ITB2021
Scheduling tasks the human way -  Brad Wood - ITB2021Scheduling tasks the human way -  Brad Wood - ITB2021
Scheduling tasks the human way - Brad Wood - ITB2021Ortus Solutions, Corp
 
NHibernate Configuration Patterns
NHibernate Configuration PatternsNHibernate Configuration Patterns
NHibernate Configuration PatternsLuca Milan
 
Fun Teaching MongoDB New Tricks
Fun Teaching MongoDB New TricksFun Teaching MongoDB New Tricks
Fun Teaching MongoDB New TricksMongoDB
 
Automation with Ansible and Containers
Automation with Ansible and ContainersAutomation with Ansible and Containers
Automation with Ansible and ContainersRodolfo Carvalho
 
Extending functionality in nginx, with modules!
Extending functionality in nginx, with modules!Extending functionality in nginx, with modules!
Extending functionality in nginx, with modules!Trygve Vea
 
Symfony2 - from the trenches
Symfony2 - from the trenchesSymfony2 - from the trenches
Symfony2 - from the trenchesLukas Smith
 
case3h231diamond.gifcase3h231energy.jpgcase3h231moder.docx
case3h231diamond.gifcase3h231energy.jpgcase3h231moder.docxcase3h231diamond.gifcase3h231energy.jpgcase3h231moder.docx
case3h231diamond.gifcase3h231energy.jpgcase3h231moder.docxtidwellveronique
 
Parallel Programming With Dot Net
Parallel Programming With Dot NetParallel Programming With Dot Net
Parallel Programming With Dot NetNeeraj Kaushik
 

Similar to C++11 Multithreading - Futures (20)

Grand Central Dispatch
Grand Central DispatchGrand Central Dispatch
Grand Central Dispatch
 
Gr8conf EU 2018 - Bring you infrastructure under control with Infrastructor
Gr8conf EU 2018 - Bring you infrastructure under control with InfrastructorGr8conf EU 2018 - Bring you infrastructure under control with Infrastructor
Gr8conf EU 2018 - Bring you infrastructure under control with Infrastructor
 
Celery
CeleryCelery
Celery
 
Celery with python
Celery with pythonCelery with python
Celery with python
 
Java util concurrent
Java util concurrentJava util concurrent
Java util concurrent
 
OOPS USING C++(UNIT 2)
OOPS USING C++(UNIT 2)OOPS USING C++(UNIT 2)
OOPS USING C++(UNIT 2)
 
Back to the future with C++ and Seastar
Back to the future with C++ and SeastarBack to the future with C++ and Seastar
Back to the future with C++ and Seastar
 
Sqlapi0.1
Sqlapi0.1Sqlapi0.1
Sqlapi0.1
 
Avoiding callback hell in Node js using promises
Avoiding callback hell in Node js using promisesAvoiding callback hell in Node js using promises
Avoiding callback hell in Node js using promises
 
Using c++Im also using a the ide editor called CodeLiteThe hea.pdf
Using c++Im also using a the ide editor called CodeLiteThe hea.pdfUsing c++Im also using a the ide editor called CodeLiteThe hea.pdf
Using c++Im also using a the ide editor called CodeLiteThe hea.pdf
 
Scheduling tasks the human way - Brad Wood - ITB2021
Scheduling tasks the human way -  Brad Wood - ITB2021Scheduling tasks the human way -  Brad Wood - ITB2021
Scheduling tasks the human way - Brad Wood - ITB2021
 
Play 2.0
Play 2.0Play 2.0
Play 2.0
 
NHibernate Configuration Patterns
NHibernate Configuration PatternsNHibernate Configuration Patterns
NHibernate Configuration Patterns
 
Fun Teaching MongoDB New Tricks
Fun Teaching MongoDB New TricksFun Teaching MongoDB New Tricks
Fun Teaching MongoDB New Tricks
 
Automation with Ansible and Containers
Automation with Ansible and ContainersAutomation with Ansible and Containers
Automation with Ansible and Containers
 
Extending functionality in nginx, with modules!
Extending functionality in nginx, with modules!Extending functionality in nginx, with modules!
Extending functionality in nginx, with modules!
 
Symfony2 - from the trenches
Symfony2 - from the trenchesSymfony2 - from the trenches
Symfony2 - from the trenches
 
case3h231diamond.gifcase3h231energy.jpgcase3h231moder.docx
case3h231diamond.gifcase3h231energy.jpgcase3h231moder.docxcase3h231diamond.gifcase3h231energy.jpgcase3h231moder.docx
case3h231diamond.gifcase3h231energy.jpgcase3h231moder.docx
 
Parallel Programming With Dot Net
Parallel Programming With Dot NetParallel Programming With Dot Net
Parallel Programming With Dot Net
 
GradleFX
GradleFXGradleFX
GradleFX
 

More from GlobalLogic Ukraine

GlobalLogic Embedded Community x ROS Ukraine Webinar "Surgical Robots"
GlobalLogic Embedded Community x ROS Ukraine Webinar "Surgical Robots"GlobalLogic Embedded Community x ROS Ukraine Webinar "Surgical Robots"
GlobalLogic Embedded Community x ROS Ukraine Webinar "Surgical Robots"GlobalLogic Ukraine
 
GlobalLogic Java Community Webinar #17 “SpringJDBC vs JDBC. Is Spring a Hero?”
GlobalLogic Java Community Webinar #17 “SpringJDBC vs JDBC. Is Spring a Hero?”GlobalLogic Java Community Webinar #17 “SpringJDBC vs JDBC. Is Spring a Hero?”
GlobalLogic Java Community Webinar #17 “SpringJDBC vs JDBC. Is Spring a Hero?”GlobalLogic Ukraine
 
GlobalLogic JavaScript Community Webinar #18 “Long Story Short: OSI Model”
GlobalLogic JavaScript Community Webinar #18 “Long Story Short: OSI Model”GlobalLogic JavaScript Community Webinar #18 “Long Story Short: OSI Model”
GlobalLogic JavaScript Community Webinar #18 “Long Story Short: OSI Model”GlobalLogic Ukraine
 
Штучний інтелект як допомога в навчанні, а не замінник.pptx
Штучний інтелект як допомога в навчанні, а не замінник.pptxШтучний інтелект як допомога в навчанні, а не замінник.pptx
Штучний інтелект як допомога в навчанні, а не замінник.pptxGlobalLogic Ukraine
 
Задачі AI-розробника як застосовується штучний інтелект.pptx
Задачі AI-розробника як застосовується штучний інтелект.pptxЗадачі AI-розробника як застосовується штучний інтелект.pptx
Задачі AI-розробника як застосовується штучний інтелект.pptxGlobalLogic Ukraine
 
Що треба вивчати, щоб стати розробником штучного інтелекту та нейромереж.pptx
Що треба вивчати, щоб стати розробником штучного інтелекту та нейромереж.pptxЩо треба вивчати, щоб стати розробником штучного інтелекту та нейромереж.pptx
Що треба вивчати, щоб стати розробником штучного інтелекту та нейромереж.pptxGlobalLogic Ukraine
 
GlobalLogic Java Community Webinar #16 “Zaloni’s Architecture for Data-Driven...
GlobalLogic Java Community Webinar #16 “Zaloni’s Architecture for Data-Driven...GlobalLogic Java Community Webinar #16 “Zaloni’s Architecture for Data-Driven...
GlobalLogic Java Community Webinar #16 “Zaloni’s Architecture for Data-Driven...GlobalLogic Ukraine
 
JavaScript Community Webinar #14 "Why Is Git Rebase?"
JavaScript Community Webinar #14 "Why Is Git Rebase?"JavaScript Community Webinar #14 "Why Is Git Rebase?"
JavaScript Community Webinar #14 "Why Is Git Rebase?"GlobalLogic Ukraine
 
GlobalLogic .NET Community Webinar #3 "Exploring Serverless with Azure Functi...
GlobalLogic .NET Community Webinar #3 "Exploring Serverless with Azure Functi...GlobalLogic .NET Community Webinar #3 "Exploring Serverless with Azure Functi...
GlobalLogic .NET Community Webinar #3 "Exploring Serverless with Azure Functi...GlobalLogic Ukraine
 
Страх і сила помилок - IT Inside від GlobalLogic Education
Страх і сила помилок - IT Inside від GlobalLogic EducationСтрах і сила помилок - IT Inside від GlobalLogic Education
Страх і сила помилок - IT Inside від GlobalLogic EducationGlobalLogic Ukraine
 
GlobalLogic .NET Webinar #2 “Azure RBAC and Managed Identity”
GlobalLogic .NET Webinar #2 “Azure RBAC and Managed Identity”GlobalLogic .NET Webinar #2 “Azure RBAC and Managed Identity”
GlobalLogic .NET Webinar #2 “Azure RBAC and Managed Identity”GlobalLogic Ukraine
 
GlobalLogic QA Webinar “What does it take to become a Test Engineer”
GlobalLogic QA Webinar “What does it take to become a Test Engineer”GlobalLogic QA Webinar “What does it take to become a Test Engineer”
GlobalLogic QA Webinar “What does it take to become a Test Engineer”GlobalLogic Ukraine
 
“How to Secure Your Applications With a Keycloak?
“How to Secure Your Applications With a Keycloak?“How to Secure Your Applications With a Keycloak?
“How to Secure Your Applications With a Keycloak?GlobalLogic Ukraine
 
GlobalLogic Machine Learning Webinar “Advanced Statistical Methods for Linear...
GlobalLogic Machine Learning Webinar “Advanced Statistical Methods for Linear...GlobalLogic Machine Learning Webinar “Advanced Statistical Methods for Linear...
GlobalLogic Machine Learning Webinar “Advanced Statistical Methods for Linear...GlobalLogic Ukraine
 
GlobalLogic Machine Learning Webinar “Statistical learning of linear regressi...
GlobalLogic Machine Learning Webinar “Statistical learning of linear regressi...GlobalLogic Machine Learning Webinar “Statistical learning of linear regressi...
GlobalLogic Machine Learning Webinar “Statistical learning of linear regressi...GlobalLogic Ukraine
 
GlobalLogic C++ Webinar “The Minimum Knowledge to Become a C++ Developer”
GlobalLogic C++ Webinar “The Minimum Knowledge to Become a C++ Developer”GlobalLogic C++ Webinar “The Minimum Knowledge to Become a C++ Developer”
GlobalLogic C++ Webinar “The Minimum Knowledge to Become a C++ Developer”GlobalLogic Ukraine
 
Embedded Webinar #17 "Low-level Network Testing in Embedded Devices Development"
Embedded Webinar #17 "Low-level Network Testing in Embedded Devices Development"Embedded Webinar #17 "Low-level Network Testing in Embedded Devices Development"
Embedded Webinar #17 "Low-level Network Testing in Embedded Devices Development"GlobalLogic Ukraine
 
GlobalLogic Webinar "Introduction to Embedded QA"
GlobalLogic Webinar "Introduction to Embedded QA"GlobalLogic Webinar "Introduction to Embedded QA"
GlobalLogic Webinar "Introduction to Embedded QA"GlobalLogic Ukraine
 
C++ Webinar "Why Should You Learn C++ in 2021-22?"
C++ Webinar "Why Should You Learn C++ in 2021-22?"C++ Webinar "Why Should You Learn C++ in 2021-22?"
C++ Webinar "Why Should You Learn C++ in 2021-22?"GlobalLogic Ukraine
 
GlobalLogic Test Automation Live Testing Session “Android Behind UI — Testing...
GlobalLogic Test Automation Live Testing Session “Android Behind UI — Testing...GlobalLogic Test Automation Live Testing Session “Android Behind UI — Testing...
GlobalLogic Test Automation Live Testing Session “Android Behind UI — Testing...GlobalLogic Ukraine
 

More from GlobalLogic Ukraine (20)

GlobalLogic Embedded Community x ROS Ukraine Webinar "Surgical Robots"
GlobalLogic Embedded Community x ROS Ukraine Webinar "Surgical Robots"GlobalLogic Embedded Community x ROS Ukraine Webinar "Surgical Robots"
GlobalLogic Embedded Community x ROS Ukraine Webinar "Surgical Robots"
 
GlobalLogic Java Community Webinar #17 “SpringJDBC vs JDBC. Is Spring a Hero?”
GlobalLogic Java Community Webinar #17 “SpringJDBC vs JDBC. Is Spring a Hero?”GlobalLogic Java Community Webinar #17 “SpringJDBC vs JDBC. Is Spring a Hero?”
GlobalLogic Java Community Webinar #17 “SpringJDBC vs JDBC. Is Spring a Hero?”
 
GlobalLogic JavaScript Community Webinar #18 “Long Story Short: OSI Model”
GlobalLogic JavaScript Community Webinar #18 “Long Story Short: OSI Model”GlobalLogic JavaScript Community Webinar #18 “Long Story Short: OSI Model”
GlobalLogic JavaScript Community Webinar #18 “Long Story Short: OSI Model”
 
Штучний інтелект як допомога в навчанні, а не замінник.pptx
Штучний інтелект як допомога в навчанні, а не замінник.pptxШтучний інтелект як допомога в навчанні, а не замінник.pptx
Штучний інтелект як допомога в навчанні, а не замінник.pptx
 
Задачі AI-розробника як застосовується штучний інтелект.pptx
Задачі AI-розробника як застосовується штучний інтелект.pptxЗадачі AI-розробника як застосовується штучний інтелект.pptx
Задачі AI-розробника як застосовується штучний інтелект.pptx
 
Що треба вивчати, щоб стати розробником штучного інтелекту та нейромереж.pptx
Що треба вивчати, щоб стати розробником штучного інтелекту та нейромереж.pptxЩо треба вивчати, щоб стати розробником штучного інтелекту та нейромереж.pptx
Що треба вивчати, щоб стати розробником штучного інтелекту та нейромереж.pptx
 
GlobalLogic Java Community Webinar #16 “Zaloni’s Architecture for Data-Driven...
GlobalLogic Java Community Webinar #16 “Zaloni’s Architecture for Data-Driven...GlobalLogic Java Community Webinar #16 “Zaloni’s Architecture for Data-Driven...
GlobalLogic Java Community Webinar #16 “Zaloni’s Architecture for Data-Driven...
 
JavaScript Community Webinar #14 "Why Is Git Rebase?"
JavaScript Community Webinar #14 "Why Is Git Rebase?"JavaScript Community Webinar #14 "Why Is Git Rebase?"
JavaScript Community Webinar #14 "Why Is Git Rebase?"
 
GlobalLogic .NET Community Webinar #3 "Exploring Serverless with Azure Functi...
GlobalLogic .NET Community Webinar #3 "Exploring Serverless with Azure Functi...GlobalLogic .NET Community Webinar #3 "Exploring Serverless with Azure Functi...
GlobalLogic .NET Community Webinar #3 "Exploring Serverless with Azure Functi...
 
Страх і сила помилок - IT Inside від GlobalLogic Education
Страх і сила помилок - IT Inside від GlobalLogic EducationСтрах і сила помилок - IT Inside від GlobalLogic Education
Страх і сила помилок - IT Inside від GlobalLogic Education
 
GlobalLogic .NET Webinar #2 “Azure RBAC and Managed Identity”
GlobalLogic .NET Webinar #2 “Azure RBAC and Managed Identity”GlobalLogic .NET Webinar #2 “Azure RBAC and Managed Identity”
GlobalLogic .NET Webinar #2 “Azure RBAC and Managed Identity”
 
GlobalLogic QA Webinar “What does it take to become a Test Engineer”
GlobalLogic QA Webinar “What does it take to become a Test Engineer”GlobalLogic QA Webinar “What does it take to become a Test Engineer”
GlobalLogic QA Webinar “What does it take to become a Test Engineer”
 
“How to Secure Your Applications With a Keycloak?
“How to Secure Your Applications With a Keycloak?“How to Secure Your Applications With a Keycloak?
“How to Secure Your Applications With a Keycloak?
 
GlobalLogic Machine Learning Webinar “Advanced Statistical Methods for Linear...
GlobalLogic Machine Learning Webinar “Advanced Statistical Methods for Linear...GlobalLogic Machine Learning Webinar “Advanced Statistical Methods for Linear...
GlobalLogic Machine Learning Webinar “Advanced Statistical Methods for Linear...
 
GlobalLogic Machine Learning Webinar “Statistical learning of linear regressi...
GlobalLogic Machine Learning Webinar “Statistical learning of linear regressi...GlobalLogic Machine Learning Webinar “Statistical learning of linear regressi...
GlobalLogic Machine Learning Webinar “Statistical learning of linear regressi...
 
GlobalLogic C++ Webinar “The Minimum Knowledge to Become a C++ Developer”
GlobalLogic C++ Webinar “The Minimum Knowledge to Become a C++ Developer”GlobalLogic C++ Webinar “The Minimum Knowledge to Become a C++ Developer”
GlobalLogic C++ Webinar “The Minimum Knowledge to Become a C++ Developer”
 
Embedded Webinar #17 "Low-level Network Testing in Embedded Devices Development"
Embedded Webinar #17 "Low-level Network Testing in Embedded Devices Development"Embedded Webinar #17 "Low-level Network Testing in Embedded Devices Development"
Embedded Webinar #17 "Low-level Network Testing in Embedded Devices Development"
 
GlobalLogic Webinar "Introduction to Embedded QA"
GlobalLogic Webinar "Introduction to Embedded QA"GlobalLogic Webinar "Introduction to Embedded QA"
GlobalLogic Webinar "Introduction to Embedded QA"
 
C++ Webinar "Why Should You Learn C++ in 2021-22?"
C++ Webinar "Why Should You Learn C++ in 2021-22?"C++ Webinar "Why Should You Learn C++ in 2021-22?"
C++ Webinar "Why Should You Learn C++ in 2021-22?"
 
GlobalLogic Test Automation Live Testing Session “Android Behind UI — Testing...
GlobalLogic Test Automation Live Testing Session “Android Behind UI — Testing...GlobalLogic Test Automation Live Testing Session “Android Behind UI — Testing...
GlobalLogic Test Automation Live Testing Session “Android Behind UI — Testing...
 

Recently uploaded

KubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlyKubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlysanyuktamishra911
 
Double rodded leveling 1 pdf activity 01
Double rodded leveling 1 pdf activity 01Double rodded leveling 1 pdf activity 01
Double rodded leveling 1 pdf activity 01KreezheaRecto
 
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...Arindam Chakraborty, Ph.D., P.E. (CA, TX)
 
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Call Girls in Nagpur High Profile
 
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance BookingCall Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance Bookingroncy bisnoi
 
Unit 2- Effective stress & Permeability.pdf
Unit 2- Effective stress & Permeability.pdfUnit 2- Effective stress & Permeability.pdf
Unit 2- Effective stress & Permeability.pdfRagavanV2
 
Work-Permit-Receiver-in-Saudi-Aramco.pptx
Work-Permit-Receiver-in-Saudi-Aramco.pptxWork-Permit-Receiver-in-Saudi-Aramco.pptx
Work-Permit-Receiver-in-Saudi-Aramco.pptxJuliansyahHarahap1
 
data_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfdata_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfJiananWang21
 
Online banking management system project.pdf
Online banking management system project.pdfOnline banking management system project.pdf
Online banking management system project.pdfKamal Acharya
 
Block diagram reduction techniques in control systems.ppt
Block diagram reduction techniques in control systems.pptBlock diagram reduction techniques in control systems.ppt
Block diagram reduction techniques in control systems.pptNANDHAKUMARA10
 
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance BookingCall Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Bookingroncy bisnoi
 
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Bookingdharasingh5698
 
Design For Accessibility: Getting it right from the start
Design For Accessibility: Getting it right from the startDesign For Accessibility: Getting it right from the start
Design For Accessibility: Getting it right from the startQuintin Balsdon
 
Intro To Electric Vehicles PDF Notes.pdf
Intro To Electric Vehicles PDF Notes.pdfIntro To Electric Vehicles PDF Notes.pdf
Intro To Electric Vehicles PDF Notes.pdfrs7054576148
 
University management System project report..pdf
University management System project report..pdfUniversity management System project report..pdf
University management System project report..pdfKamal Acharya
 
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Bookingdharasingh5698
 

Recently uploaded (20)

Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024
 
KubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlyKubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghly
 
Double rodded leveling 1 pdf activity 01
Double rodded leveling 1 pdf activity 01Double rodded leveling 1 pdf activity 01
Double rodded leveling 1 pdf activity 01
 
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak HamilCara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
 
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
 
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
 
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance BookingCall Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
 
Unit 2- Effective stress & Permeability.pdf
Unit 2- Effective stress & Permeability.pdfUnit 2- Effective stress & Permeability.pdf
Unit 2- Effective stress & Permeability.pdf
 
Work-Permit-Receiver-in-Saudi-Aramco.pptx
Work-Permit-Receiver-in-Saudi-Aramco.pptxWork-Permit-Receiver-in-Saudi-Aramco.pptx
Work-Permit-Receiver-in-Saudi-Aramco.pptx
 
data_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfdata_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdf
 
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
 
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar ≼🔝 Delhi door step de...
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar  ≼🔝 Delhi door step de...Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar  ≼🔝 Delhi door step de...
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar ≼🔝 Delhi door step de...
 
Online banking management system project.pdf
Online banking management system project.pdfOnline banking management system project.pdf
Online banking management system project.pdf
 
Block diagram reduction techniques in control systems.ppt
Block diagram reduction techniques in control systems.pptBlock diagram reduction techniques in control systems.ppt
Block diagram reduction techniques in control systems.ppt
 
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance BookingCall Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
 
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
 
Design For Accessibility: Getting it right from the start
Design For Accessibility: Getting it right from the startDesign For Accessibility: Getting it right from the start
Design For Accessibility: Getting it right from the start
 
Intro To Electric Vehicles PDF Notes.pdf
Intro To Electric Vehicles PDF Notes.pdfIntro To Electric Vehicles PDF Notes.pdf
Intro To Electric Vehicles PDF Notes.pdf
 
University management System project report..pdf
University management System project report..pdfUniversity management System project report..pdf
University management System project report..pdf
 
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
 

C++11 Multithreading - Futures

  • 2. Introduction Motivation Asynchronous Return Object: • future<T> Asynchronous Provider Objects: • async<F, Args…> • packaged_task<R, Args…> • promise<T> Continuation passing style Q&A
  • 3. [C++03, 1.9.6] • The observable behavior of the abstract machine is its sequence of reads and writes to volatile data and calls to library I/O functions.  [C++11, 1.10.1]: • A thread of execution (also known as a thread) is a single flow of control within a program... The execution of the entire program consists of an execution of all of its threads...
  • 4.  [C++11, 30.1.1]: • The following subclauses describe components to create and manage threads (1.10), perform mutual exclusion, and communicate conditions and values between threads… Subclause Header Threads <thread> Mutual exclusion <mutex> Condition variables <condition_variable> Futures <future>
  • 5. Having independent time consuming tasks: // ... device target_device; target_device.initialize(); // <- time consuming configuration_storage db; configuration config; db.load(config); // <- time consuming target_device.configure(config);
  • 6. Execute time consuming tasks simultaneously, naive approach: // ... configuration_storage db; configuration config; thread loader([&db, &config]{ db.load(config); }); // <- run loading config in a separate thread device target_device; target_device.initialize(); // <- continue device initialization in current thread loader.join(); // <- assume loading done at this point target_device.configure(config);
  • 7. Execute time consuming tasks simultaneously, thread pool approach: class async_exec_service { public: void exec(function<void()> f); }; // ... async_exec_service exec_service; // ... configuration_storage db; configuration config; exec_service.exec([&db, &config]{ db.load(config); }); // <- run loading config in the thread pool device target_device; target_device.initialize(); // <- continue device initialization in current thread // hmmm... are we ready for proceed ??? target_device.configure(config);
  • 8.  Execute time consuming tasks simultaneously, thread pool approach with synchronization: class async_exec_service { public: void exec(function<void()> f); }; // ... async_exec_service exec_service; // ... configuration_storage db; unique_ptr<configuration> config; mutex config_guard; condition_variable config_cv; exec_service.exec([&]{ unique_lock<mutex> lock(config_guard); config.reset(new configuration); db.load(*config); config_cv.notify_one(); }); // <- run loading config in the thread pool device target_device; target_device.initialize(); // continue device initialization in current thread { // wait for configuration loading done unique_lock<mutex> lock(config_guard); config_cv.wait(lock, [&]{ return (config != nullptr); }); } // we are ready for proceed target_device.configure(*config);
  • 9. The Standard Library provides a unified solution communicate data between threads: • shared state object – privately held object with a placeholder for result and some auxiliary data; • asynchronous return object – reads result from a shared state; • asynchronous provider - provides shared state object with a value.
  • 10. SharedState – internal shared state; future – asynchronous return object; Setter – asynchronous provider object: • async • packaged_task • promise
  • 11.  Execute time consuming tasks simultaneously, using future<T>: class async_exec_service { public: template <typename _Function> auto exec(_Function&& f) -> future<decltype(f())> { /*...*/ } }; async_exec_service exec_service; // ... configuration_storage db; future<configuration> config = exec_service.exec([&db]{ configuration config; db.load(config); return config; }); device target_device; target_device.initialize(); target_device.configure(config.get()); // wait for result and proceed
  • 12. valid() – tests if the future has a shared state; get() – retrieves value, wait if needed; wait()/wait_for(delay)/wait_until(time) – waits the future to be populated with result; share() – makes shared_future from this future; invalidates this future object.
  • 13. shares its shared state object between several asynchronous return objects: the main purpose – signal the result is ready to multiple waiting threads
  • 14. Runs a function in a separate thread and set its result to future: • step back to naive approach: configuration_storage db; future<configuration> config = async([&db]{ configuration config; db.load(config); return config; }); // run loading config in a separate thread device target_device; target_device.initialize(); // continue device initialization in current thread target_device.configure(config.get());
  • 15. template< class Function, class... Args> result_type async(Function&& f, Args&&... args); template< class Function, class... Args > result_type async(launch policy, Function&& f, Args&&... args); async launch policy:  launch::async – launch a new thread for execution;  launch::deferred – defers the execution until the returned future value accessed; performs execution in current thread;  launch::async|launch::deferred – used by default, allows the implementation to choose one.
  • 16. configuration_storage db; future<configuration> config = async([&db]{ configuration config; db.load(config); return config; }); // run loading config in a separate thread device target_device; if (!target_device.initialize()) { return; // what will happen to config here ??? } target_device.configure(config.get());  [3.6.8/5]: • … If the implementation chooses the launch::async policy, - a call to a waiting function on an asynchronous return object that shares the shared state created by this async call shall block until the associated thread has completed, as if joined; …
  • 17.  provides better control over execution;  does not execute threads itself;  provides a wrapper on a function or a callable object for store returned value/exception in a future. configuration_storage db; packaged_task<configuration ()> load_config([&db] { configuration config; db.load(config); return config; }); future<configuration> config = load_config.get_future(); // just get future<> for future :) load_config(); // loading config goes here device target_device; target_device.initialize(); target_device.configure(config.get());
  • 18.  Implementation for async_exec_service: class async_exec_service { queue<function<void ()>> _exec_queue; // worker threads will take functions from _exec_queue // ... void enqueue(function<void ()> task) {/* put task to _exec_queue */} public: template <typename _Function> auto exec(_Function&& f) -> future<decltype(f())> { typedef decltype(f()) _Result; shared_ptr<packaged_task<_Result()>> task = make_shared<packaged_task<_Result()>>(f); function<void()> task_wrapper = [task]{(*task)();}; enqueue(task_wrapper); return task->get_future(); } // ... };
  • 19.  provides the highest level of control over the shared state;  does not require a function or callable object for populate shared state;  requires executing thread explicitly set value/exception to shared state.
  • 20.  Yet another implementation for async_exec_service: class async_exec_service { queue<function<void ()>> _exec_queue; // worker threads will take functions from _exec_queue // ... void enqueue(function<void ()> task) {/* put task to _exec_queue */} public: template <typename _Function> auto exec(_Function&& f) -> future<decltype(f())> { typedef decltype(f()) _Result; shared_ptr<promise<_Result>> result = make_shared<promise<_Result>>(); function<void()> task_wrapper = [result, f]{ try { result->set_value(f()); } catch (...) { result->set_exception(current_exception()); } } enqueue(task_wrapper); return result->get_future(); } };
  • 22. Currently is not a part of C++ Standard Going to be included in C++17 (N3857) Already available in boost
  • 23.  compose two futures by declaring one to be the continuation of another: device target_device; configuration_storage db; future<void> configure = async([&db]{ configuration config; db.load(config); return config; }).then([&target_device](future<configuration> config){ // JUST FOR EXAMPLE: // config is ready at this point, // but it doesn’t mean we could already configure the device }); target_device.initialize();
  • 24.  wait a number of futures for at least one to be ready: device target_device; configuration_storage db; configuration config; future<bool> tasks[] = { async([&target_device]{ return target_device.initialize(); }), async([&db, &config]{ db.load(config); return true; }), }; future<vector<future<bool>>> anyone = when_any(begin(tasks), end(tasks)); future<bool> anyone_completed = anyone.then( [](future<vector<future<bool>>> lst) { // JUST FOR EXAMPLE for (future<bool>& f: lst) { if (f.is_ready()) return f.get(); // won't block here } });
  • 25.  wait for a number of futures to be ready: device target_device; configuration_storage db; future<bool> init_device = async([&target_device]{ return target_device.initialize(); }); future<configuration> load_config = async([&db]{ configuration config; db.load(config); return config; }); future<tuple<future<bool>, future<configuration>>> init_all = when_all(init_device, load_config); future<bool> device_ready = init_all.then( [&target_device](tuple<future<bool>, future<configuration>> params){ bool hw_ok = get<0>().get(); if (!hw_ok) return false; configuration config = get<1>().get(); target_device.configure(config); return true; } );