SlideShare a Scribd company logo
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 features
india_mani
 
srgoc
srgocsrgoc
C++aptitude questions and answers
C++aptitude questions and answersC++aptitude questions and answers
C++aptitude questions and answers
sheibansari
 
classes & objects in cpp overview
classes & objects in cpp overviewclasses & objects in cpp overview
classes & objects in cpp overview
gourav kottawar
 
Link list
Link listLink list
Link list
Malainine Zaid
 
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
Pavan Chitumalla
 
DRYing to Monad in Java8
DRYing to Monad in Java8DRYing to Monad in Java8
DRYing to Monad in Java8
Dhaval Dalal
 
data Structure Lecture 1
data Structure Lecture 1data Structure Lecture 1
data Structure Lecture 1
Teksify
 
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
Dawid Rusnak
 
Advanced Java Practical File
Advanced Java Practical FileAdvanced Java Practical File
Advanced Java Practical File
Soumya Behera
 
A Taste of Dotty
A Taste of DottyA Taste of Dotty
A Taste of Dotty
Hermann Hueck
 
Александр Гранин, Функциональная 'Жизнь': параллельные клеточные автоматы и к...
Александр Гранин, Функциональная 'Жизнь': параллельные клеточные автоматы и к...Александр Гранин, Функциональная 'Жизнь': параллельные клеточные автоматы и к...
Александр Гранин, Функциональная 'Жизнь': параллельные клеточные автоматы и к...
Sergey Platonov
 
Thread
ThreadThread
Thread
phanleson
 
iOS Session-2
iOS Session-2iOS Session-2
iOS Session-2
Hussain Behestee
 
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
Alexander Gladysh
 
Uncommon Design Patterns
Uncommon Design PatternsUncommon Design Patterns
Uncommon Design Patterns
Stefano Fago
 
12. stl örnekler
12.  stl örnekler12.  stl örnekler
12. stl örnekler
karmuhtam
 
Java_practical_handbook
Java_practical_handbookJava_practical_handbook
Java_practical_handbook
Manusha Dilan
 
Concurrency Concepts in Java
Concurrency Concepts in JavaConcurrency Concepts in Java
Concurrency Concepts in Java
Doug Hawkins
 
Java 8 Workshop
Java 8 WorkshopJava 8 Workshop
Java 8 Workshop
Mario Fusco
 

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 Dispatch
cqtt191
 
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
Stanislav Tiurikov
 
Celery
CeleryCelery
Celery with python
Celery with pythonCelery with python
Celery with python
Alexandre González Rodríguez
 
Java util concurrent
Java util concurrentJava util concurrent
Java util concurrent
Roger 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 Seastar
Tzach Livyatan
 
Sqlapi0.1
Sqlapi0.1Sqlapi0.1
Sqlapi0.1
jitendral
 
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
Ankit 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.pdf
fashiongallery1
 
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
Ortus Solutions, Corp
 
Play 2.0
Play 2.0Play 2.0
Play 2.0
elizhender
 
NHibernate Configuration Patterns
NHibernate Configuration PatternsNHibernate Configuration Patterns
NHibernate Configuration Patterns
Luca Milan
 
Fun Teaching MongoDB New Tricks
Fun Teaching MongoDB New TricksFun Teaching MongoDB New Tricks
Fun Teaching MongoDB New Tricks
MongoDB
 
Automation with Ansible and Containers
Automation with Ansible and ContainersAutomation with Ansible and Containers
Automation with Ansible and Containers
Rodolfo 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 trenches
Lukas Smith
 
case3h231diamond.gifcase3h231energy.jpgcase3h231moder.docx
case3h231diamond.gifcase3h231energy.jpgcase3h231moder.docxcase3h231diamond.gifcase3h231energy.jpgcase3h231moder.docx
case3h231diamond.gifcase3h231energy.jpgcase3h231moder.docx
tidwellveronique
 
Parallel Programming With Dot Net
Parallel Programming With Dot NetParallel Programming With Dot Net
Parallel Programming With Dot Net
Neeraj Kaushik
 
GradleFX
GradleFXGradleFX

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 Java Community Webinar #18 “How to Improve Web Application Perfor...
GlobalLogic Java Community Webinar #18 “How to Improve Web Application Perfor...GlobalLogic Java Community Webinar #18 “How to Improve Web Application Perfor...
GlobalLogic Java Community Webinar #18 “How to Improve Web Application Perfor...
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
Штучний інтелект як допомога в навчанні, а не замінник.pptx
GlobalLogic Ukraine
 
Задачі AI-розробника як застосовується штучний інтелект.pptx
Задачі AI-розробника як застосовується штучний інтелект.pptxЗадачі AI-розробника як застосовується штучний інтелект.pptx
Задачі AI-розробника як застосовується штучний інтелект.pptx
GlobalLogic Ukraine
 
Що треба вивчати, щоб стати розробником штучного інтелекту та нейромереж.pptx
Що треба вивчати, щоб стати розробником штучного інтелекту та нейромереж.pptxЩо треба вивчати, щоб стати розробником штучного інтелекту та нейромереж.pptx
Що треба вивчати, щоб стати розробником штучного інтелекту та нейромереж.pptx
GlobalLogic 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 Education
GlobalLogic 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
 

More from GlobalLogic Ukraine (20)

GlobalLogic Java Community Webinar #18 “How to Improve Web Application Perfor...
GlobalLogic Java Community Webinar #18 “How to Improve Web Application Perfor...GlobalLogic Java Community Webinar #18 “How to Improve Web Application Perfor...
GlobalLogic Java Community Webinar #18 “How to Improve Web Application Perfor...
 
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?"
 

Recently uploaded

Updated Limitations of Simplified Methods for Evaluating the Potential for Li...
Updated Limitations of Simplified Methods for Evaluating the Potential for Li...Updated Limitations of Simplified Methods for Evaluating the Potential for Li...
Updated Limitations of Simplified Methods for Evaluating the Potential for Li...
Robert Pyke
 
Defect Elimination Management - CMMS Success.pdf
Defect Elimination Management - CMMS Success.pdfDefect Elimination Management - CMMS Success.pdf
Defect Elimination Management - CMMS Success.pdf
David Johnston
 
Future Networking v Energy Limits ICTON 2024 Bari Italy
Future Networking v Energy Limits ICTON 2024 Bari ItalyFuture Networking v Energy Limits ICTON 2024 Bari Italy
Future Networking v Energy Limits ICTON 2024 Bari Italy
University of Hertfordshire
 
Sea Wave Energy - Renewable Energy Resources
Sea Wave Energy - Renewable Energy ResourcesSea Wave Energy - Renewable Energy Resources
Sea Wave Energy - Renewable Energy Resources
21h16charis
 
Introduction to Power System Engingeering
Introduction to Power System EngingeeringIntroduction to Power System Engingeering
Introduction to Power System Engingeering
Zamir Fatemi
 
UNIT-I-METAL CASTING PROCESSES -Manufact
UNIT-I-METAL CASTING PROCESSES -ManufactUNIT-I-METAL CASTING PROCESSES -Manufact
UNIT-I-METAL CASTING PROCESSES -Manufact
Mr.C.Dineshbabu
 
Machine Learning_SVM_KNN_K-MEANSModule 2.pdf
Machine Learning_SVM_KNN_K-MEANSModule 2.pdfMachine Learning_SVM_KNN_K-MEANSModule 2.pdf
Machine Learning_SVM_KNN_K-MEANSModule 2.pdf
Dr. Shivashankar
 
III B.TECH CSE_flutter Lab manual (1).docx
III B.TECH CSE_flutter Lab manual (1).docxIII B.TECH CSE_flutter Lab manual (1).docx
III B.TECH CSE_flutter Lab manual (1).docx
divijareddy0502
 
PBL _PPT _final year for engineerin student
PBL _PPT _final  year for engineerin studentPBL _PPT _final  year for engineerin student
PBL _PPT _final year for engineerin student
nikitalohar549
 
Agricultural Profitability through Resilience: Smallholder Farmers' Strategie...
Agricultural Profitability through Resilience: Smallholder Farmers' Strategie...Agricultural Profitability through Resilience: Smallholder Farmers' Strategie...
Agricultural Profitability through Resilience: Smallholder Farmers' Strategie...
IJAEMSJORNAL
 
THERMAL POWER PLANT its applications and advantages
THERMAL POWER PLANT its applications and advantagesTHERMAL POWER PLANT its applications and advantages
THERMAL POWER PLANT its applications and advantages
VikramSingh6251
 
FIRE OUTBREAK EMERGENCY FINAL REPORT.pdf
FIRE OUTBREAK EMERGENCY FINAL REPORT.pdfFIRE OUTBREAK EMERGENCY FINAL REPORT.pdf
FIRE OUTBREAK EMERGENCY FINAL REPORT.pdf
Dar es Salaam, Tanzania
 
r4.OReilly.Hadoop.The.Definitive.Guide.4th.Edition.2015.pdf
r4.OReilly.Hadoop.The.Definitive.Guide.4th.Edition.2015.pdfr4.OReilly.Hadoop.The.Definitive.Guide.4th.Edition.2015.pdf
r4.OReilly.Hadoop.The.Definitive.Guide.4th.Edition.2015.pdf
ArunKumar750226
 
Modified O-RAN 5G Edge Reference Architecture using RNN
Modified O-RAN 5G Edge Reference Architecture using RNNModified O-RAN 5G Edge Reference Architecture using RNN
Modified O-RAN 5G Edge Reference Architecture using RNN
ijwmn
 
RAILWAYS, a vital part of our infrastructure, play a crucial role in ensuring...
RAILWAYS, a vital part of our infrastructure, play a crucial role in ensuring...RAILWAYS, a vital part of our infrastructure, play a crucial role in ensuring...
RAILWAYS, a vital part of our infrastructure, play a crucial role in ensuring...
Kiran Kumar Manigam
 
The Transformation Risk-Benefit Model of Artificial Intelligence: Balancing R...
The Transformation Risk-Benefit Model of Artificial Intelligence: Balancing R...The Transformation Risk-Benefit Model of Artificial Intelligence: Balancing R...
The Transformation Risk-Benefit Model of Artificial Intelligence: Balancing R...
gerogepatton
 
414565650-Mixing-and-Agglomeration-in-Eirich-Mixers.pdf
414565650-Mixing-and-Agglomeration-in-Eirich-Mixers.pdf414565650-Mixing-and-Agglomeration-in-Eirich-Mixers.pdf
414565650-Mixing-and-Agglomeration-in-Eirich-Mixers.pdf
RanjanKumarPATEL4
 
Youtube Transcript Sumariser- application of API
Youtube Transcript Sumariser- application of APIYoutube Transcript Sumariser- application of API
Youtube Transcript Sumariser- application of API
AnamikaRani12
 
Mobile Forensics challenges and Extraction process
Mobile Forensics challenges and Extraction processMobile Forensics challenges and Extraction process
Mobile Forensics challenges and Extraction process
Swapnil Gharat
 
software engineering software engineering
software engineering software engineeringsoftware engineering software engineering
software engineering software engineering
PrabhuB33
 

Recently uploaded (20)

Updated Limitations of Simplified Methods for Evaluating the Potential for Li...
Updated Limitations of Simplified Methods for Evaluating the Potential for Li...Updated Limitations of Simplified Methods for Evaluating the Potential for Li...
Updated Limitations of Simplified Methods for Evaluating the Potential for Li...
 
Defect Elimination Management - CMMS Success.pdf
Defect Elimination Management - CMMS Success.pdfDefect Elimination Management - CMMS Success.pdf
Defect Elimination Management - CMMS Success.pdf
 
Future Networking v Energy Limits ICTON 2024 Bari Italy
Future Networking v Energy Limits ICTON 2024 Bari ItalyFuture Networking v Energy Limits ICTON 2024 Bari Italy
Future Networking v Energy Limits ICTON 2024 Bari Italy
 
Sea Wave Energy - Renewable Energy Resources
Sea Wave Energy - Renewable Energy ResourcesSea Wave Energy - Renewable Energy Resources
Sea Wave Energy - Renewable Energy Resources
 
Introduction to Power System Engingeering
Introduction to Power System EngingeeringIntroduction to Power System Engingeering
Introduction to Power System Engingeering
 
UNIT-I-METAL CASTING PROCESSES -Manufact
UNIT-I-METAL CASTING PROCESSES -ManufactUNIT-I-METAL CASTING PROCESSES -Manufact
UNIT-I-METAL CASTING PROCESSES -Manufact
 
Machine Learning_SVM_KNN_K-MEANSModule 2.pdf
Machine Learning_SVM_KNN_K-MEANSModule 2.pdfMachine Learning_SVM_KNN_K-MEANSModule 2.pdf
Machine Learning_SVM_KNN_K-MEANSModule 2.pdf
 
III B.TECH CSE_flutter Lab manual (1).docx
III B.TECH CSE_flutter Lab manual (1).docxIII B.TECH CSE_flutter Lab manual (1).docx
III B.TECH CSE_flutter Lab manual (1).docx
 
PBL _PPT _final year for engineerin student
PBL _PPT _final  year for engineerin studentPBL _PPT _final  year for engineerin student
PBL _PPT _final year for engineerin student
 
Agricultural Profitability through Resilience: Smallholder Farmers' Strategie...
Agricultural Profitability through Resilience: Smallholder Farmers' Strategie...Agricultural Profitability through Resilience: Smallholder Farmers' Strategie...
Agricultural Profitability through Resilience: Smallholder Farmers' Strategie...
 
THERMAL POWER PLANT its applications and advantages
THERMAL POWER PLANT its applications and advantagesTHERMAL POWER PLANT its applications and advantages
THERMAL POWER PLANT its applications and advantages
 
FIRE OUTBREAK EMERGENCY FINAL REPORT.pdf
FIRE OUTBREAK EMERGENCY FINAL REPORT.pdfFIRE OUTBREAK EMERGENCY FINAL REPORT.pdf
FIRE OUTBREAK EMERGENCY FINAL REPORT.pdf
 
r4.OReilly.Hadoop.The.Definitive.Guide.4th.Edition.2015.pdf
r4.OReilly.Hadoop.The.Definitive.Guide.4th.Edition.2015.pdfr4.OReilly.Hadoop.The.Definitive.Guide.4th.Edition.2015.pdf
r4.OReilly.Hadoop.The.Definitive.Guide.4th.Edition.2015.pdf
 
Modified O-RAN 5G Edge Reference Architecture using RNN
Modified O-RAN 5G Edge Reference Architecture using RNNModified O-RAN 5G Edge Reference Architecture using RNN
Modified O-RAN 5G Edge Reference Architecture using RNN
 
RAILWAYS, a vital part of our infrastructure, play a crucial role in ensuring...
RAILWAYS, a vital part of our infrastructure, play a crucial role in ensuring...RAILWAYS, a vital part of our infrastructure, play a crucial role in ensuring...
RAILWAYS, a vital part of our infrastructure, play a crucial role in ensuring...
 
The Transformation Risk-Benefit Model of Artificial Intelligence: Balancing R...
The Transformation Risk-Benefit Model of Artificial Intelligence: Balancing R...The Transformation Risk-Benefit Model of Artificial Intelligence: Balancing R...
The Transformation Risk-Benefit Model of Artificial Intelligence: Balancing R...
 
414565650-Mixing-and-Agglomeration-in-Eirich-Mixers.pdf
414565650-Mixing-and-Agglomeration-in-Eirich-Mixers.pdf414565650-Mixing-and-Agglomeration-in-Eirich-Mixers.pdf
414565650-Mixing-and-Agglomeration-in-Eirich-Mixers.pdf
 
Youtube Transcript Sumariser- application of API
Youtube Transcript Sumariser- application of APIYoutube Transcript Sumariser- application of API
Youtube Transcript Sumariser- application of API
 
Mobile Forensics challenges and Extraction process
Mobile Forensics challenges and Extraction processMobile Forensics challenges and Extraction process
Mobile Forensics challenges and Extraction process
 
software engineering software engineering
software engineering software engineeringsoftware engineering software engineering
software engineering software engineering
 

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; } );