SlideShare a Scribd company logo
1 of 35
Download to read offline
NATURAL TASK SCHEDULING
Using Futures and Continuations
Qt Developer Days 2013
Ivan Čukić
ivan.cukic@kde.org
ivan.fomentgroup.org/blog
THE PROBLEM
Meet Jeff
Out of Control
Reasons for Waiting
The Problem Continuations Schedulers Tasks Epilogue
MEET JEFF
3
The Problem Continuations Schedulers Tasks Epilogue
MEET JEFF
void login()
{
user = get_username();
new_user = !check_if_user_exists(user);
if (new_user) {
pass = get_password();
initialize_account(uame, pass);
} else do {
pass = get_password();
} while (!check_user(user, pass));
initialize_environment();
if (new_user) show_welcome_message();
}
4
The Problem Continuations Schedulers Tasks Epilogue
MEET JEFF
void login() { get_username(on_got_username); }
void on_got_username( ::: ) {
new_user = !check_if_user_exists(user);
if (new_user) {
get_password(on_got_password);
} else { ::: }
}
void on_got_password( ::: ) {
check_user(user, password, on_user_checked);
}
void on_user_checked( ::: ) {
if (!user_valid) {
on_got_username(user);
} else {
initialize_environment(on_environment_initialized);
}
}
:::
5
The Problem Continuations Schedulers Tasks Epilogue
OUT OF CONTROL
6
The Problem Continuations Schedulers Tasks Epilogue
OUT OF CONTROL
“Spaghetti code” by George W. Hart
7
The Problem Continuations Schedulers Tasks Epilogue
REASONS FOR WAITING
User input
Network actions
Inter-process
communication
External process
execution
Communication with
a slow database
CPU-intensive work
Heterogeneous
computing
...
8
The Problem Continuations Schedulers Tasks Epilogue
HIDEAWAY
Wrapping it in task objects (QThread, KJob, ...)
Methods with time-outs (select, ...)
... or with validity checks (QProcess::state, ...)
Future values (future<T>, QFuture<T>,
QDBusPendingReply<T>, ...)
9
CONTINUATIONS
Lost in the Future
Under wraps
The Problem Continuations Schedulers Tasks Epilogue
LOST IN THE FUTURE
Is it about monads?
Callbacks?
Signals and slots?
11
The Problem Continuations Schedulers Tasks Epilogue
LOST IN THE FUTURE
C++ standard proposal N3558, Boost.Thread 1.55.0
future<int> result = deepThought.meaningOfLife();
#if 0
// this would block
cout << result.get();
#endif
result.then([] (future<int> result) {
// called when the result is available
// call to .get() does not block here
cout << result.get();
});
12
The Problem Continuations Schedulers Tasks Epilogue
LOST IN THE FUTURE
|
int i; | i.then(c); // ERROR!
|
future<int> future; | future.then(c); // ok
|
QFuture<int> qfuture; | qfuture.then(c); // ERROR!
|
|
|
|
|
|
|
|
KJob *job; | job->then(c); // ERROR!
|
|
|
|
|
|
13
The Problem Continuations Schedulers Tasks Epilogue
LOST IN THE FUTURE
|
int i; | c(i);
|
future<int> future; | future.then(c);
|
QFuture<int> qfuture; | auto watcher = new QFutureWatcher<int>();
| QObject::connect(watcher,
| &QFutureWatcherBase::finished,
| [=] {
| c(watcher->result());
| watcher->deleteLater();
| });
| watcher->setFuture(qfuture);
|
KJob *job; | QObject::connect(job,
| &KJob::finished,
| [] (KJob *job) {
| c(job-> ... something ...);
| job->deleteLater();
| });
|
14
The Problem Continuations Schedulers Tasks Epilogue
UNDER WRAPS
template <typename _Job, typename _Continuation>
void continue_with(_Job &&job, _Continuation &&continuation)
{
using is_nullary =
typename std::is_constructible<
std::function<void()>,
_Continuation
>::type;
_continue_with_helper(
job(),
std::forward<_Continuation>(continuation), is_nullary()
);
}
15
The Problem Continuations Schedulers Tasks Epilogue
UNDER WRAPS
template <typename _ReturnType, typename _Continuation>
void _continue_with_helper(const _ReturnType &value,
_Continuation &&continuation,
std::true_type)
{
continuation();
}
template <typename _ReturnType, typename _Continuation>
void _continue_with_helper(const _ReturnType &value,
_Continuation &&continuation,
std::false_type)
{
using is_callable = ...;
static_assert(is_callable::value,
"The continuation needs to have zero or one argument");
continuation(value);
}
16
The Problem Continuations Schedulers Tasks Epilogue
UNDER WRAPS
template <typename _ReturnType, typename _Continuation>
void _continue_with_helper(const QFuture<_ReturnType> &future,
_Continuation &&continuation,
std::false_type)
{
if (!future.isFinished()) {
auto watcher =
new QFutureWatcher<_ReturnType>();
QObject::connect(watcher, &QFutureWatcherBase::finished,
[=] {
continuation(watcher->result());
watcher->deleteLater();
});
watcher->setFuture(future);
} else continuation(future.result());
}
17
The Problem Continuations Schedulers Tasks Epilogue
MATCHBOX
template<typename _TestType, typename _ArgType>
class has_then_method {
private:
template<typename U, void (U::*)(_ArgType)>
struct test_struct {};
template<typename U>
static std::true_type test(test_struct <U, &U::then> *);
template<typename U>
static std::false_type test(...);
public:
using type = decltype(test<_TestType>(nullptr));
static const bool value =
std::is_same<type, std::true_type>::value;
}
18
SCHEDULERS
The Chains are On
The New Order
Set Your Controls for the Heart of the Sun
The Problem Continuations Schedulers Tasks Epilogue
THE CHAINS ARE ON
getUsername().then(
[] (future<string> username) {
getPassword().then(
[=] (future<string> password) {
createAccount(username, password).then(
...
);
}
);
}
);
Localized, but still not readable. Can it be made nicer?
20
The Problem Continuations Schedulers Tasks Epilogue
THE CHAINS ARE ON
Can it be made to look like this?
void login()
{
...
username = getUsername();
password = getPassword();
createAccount(username, password);
}
No, but ...
21
The Problem Continuations Schedulers Tasks Epilogue
THE CHAINS ARE ON
... it could look like this:
auto login = serial_
(
...
username = getUsername(),
password = getPassword(),
createAccount(username, password)
);
Peculiar syntax, but much more readable.
22
The Problem Continuations Schedulers Tasks Epilogue
THE NEW ORDER
template <typename... _Jobs>
class Serial;
template <>
class Serial<> : public QObject
, protected QFutureInterface<int> {
public:
~Serial() {}
int operator()()
{
reportResult(0);
reportFinished();
return 0;
}
};
23
The Problem Continuations Schedulers Tasks Epilogue
THE NEW ORDER
template <typename _Job, typename... _Jobs>
class Serial<_Job, _Jobs...> : public Serial<_Jobs...> {
private:
using tail_t = Serial<_Jobs...>;
public:
Serial(_Job &&job, _Jobs &&... jobs)
: tail_t(std::forward<_Jobs>(jobs)...)
, m_job(std::forward<_Job>(job)) {}
QFuture<int> operator()() {
auto future = this->future();
continue_with(std::ref(m_job), [&] {
tail_t::operator()();
});
return future;
}
private:
_Job m_job;
};
24
The Problem Continuations Schedulers Tasks Epilogue
LET THERE BE MORE LIGHT
while loop:
while_( | while_(condition) (
condition, | body
body |
) | )
branching:
if_( | if_(condition) (
condition, | then_branch
then_branch, | ).else_(
else_branch | else_branch
) | )
25
The Problem Continuations Schedulers Tasks Epilogue
LET THERE BE MORE LIGHT
asynchronous assignment
var<int> value;
value = 5; // immediate assignment
value = someFuture(); // asynchronous assignment
parallel execution
parallel_(
task1,
task2,
...
)
parallel without waiting
detach_(task)
producer-consumer
transactions
...
26
The Problem Continuations Schedulers Tasks Epilogue
SET YOUR CONTROLS...
var<int> wait;
serial_(
test::writeMessage(0, "Starting the program"),
wait = test::howMuchShouldIWait(7),
test::writeMessageAsync(wait,
"What is the answer to the Ultimate Question of Life, "
"the Universe, and Everything?"
),
while_(test::howMuchShouldIWait(0),
test::writeMessageAsync(1, "42")
),
serial_(
test::writeMessageAsync(1, "We are going away..."),
test::writeMessageAsync(1, "... sorry, but we have to.")
),
test::writeMessage(0, "There, you have it!")
)();
27
The Problem Continuations Schedulers Tasks Epilogue
... FOR THE HEART OF THE SUN
while_(
// Wait until we get a connection.
client = ws::server::accept(server),
// Start a detached execution path to process the client.
detach_([] {
var<ws::client_header> header;
var<ws::message> message;
var<string> server_key;
serial_(
// WebSocket handshake
header = ws::client::get_header(),
server_key = ws::server::create_key(header),
ws::client::send_header(client, server_key),
// Sending the initial greeting message
ws::client::message_write(client, "Hello, I’m Echo"),
// Connection established
while_(
// getting and echoing the message
message = ws::client::message_read(client),
ws::client::message_write(client, message)
)
)
})
)
28
TASKS
Lazy Day
The Problem Continuations Schedulers Tasks Epilogue
LAZY DAY
Problem:
A method is executed while the arguments are evaluated.
serial_(
someMethod(0, "Starting the program"),
...
);
someMethod must not do anything, but return a functor.
30
The Problem Continuations Schedulers Tasks Epilogue
LAZY DAY
So, your options are:
void someMethod(...);
serial_(
std::bind(someMethod, 0, "Starting the program"),
...
)
31
The Problem Continuations Schedulers Tasks Epilogue
LAZY DAY
Or using a std::bind-based wrapper
namespace detail {
void someMethod(...);
}
auto someMethod(...)
-> decltype(std::bind(detail::someMethod,
std::forward arguments ...))
{
return std::bind(detail::someMethod,
std::forward arguments ...);
}
serial_(
someMethod(0, "Starting the program"),
...
)
32
The Problem Continuations Schedulers Tasks Epilogue
LAZY DAY
Or using a simple wrapper:
namespace detail {
void someMethod(...);
}
auto someMethod = curry(detail::someMethod);
serial_(
someMethod(0, "Starting the program"),
...
)
33
The Problem Continuations Schedulers Tasks Epilogue
EPILOGUE
Benefits:
Readable code, easy to reason about
Automatic lifetime management
Advanced control structures compared to plain C++
Things to get used to:
Peculiar syntax
Some functional programming constructs like
purity, immutability, etc. are preferred
Less expressive statements
34
The Problem Continuations Schedulers Tasks Epilogue
ANSWERS? QUESTIONS! QUESTIONS? ANSWERS!
Kudos:
Friends at KDE
Dr Saša Malkov
KDAB
basysKom
LATEX and Beamer developers
35

More Related Content

What's hot

My app is secure... I think
My app is secure... I thinkMy app is secure... I think
My app is secure... I thinkWim Godden
 
My app is secure... I think
My app is secure... I thinkMy app is secure... I think
My app is secure... I thinkWim Godden
 
jQuery Bay Area Conference 2010
jQuery Bay Area Conference 2010jQuery Bay Area Conference 2010
jQuery Bay Area Conference 2010mennovanslooten
 
What's up with Prototype and script.aculo.us?
What's up with Prototype and script.aculo.us?What's up with Prototype and script.aculo.us?
What's up with Prototype and script.aculo.us?Christophe Porteneuve
 
Basic Tutorial of React for Programmers
Basic Tutorial of React for ProgrammersBasic Tutorial of React for Programmers
Basic Tutorial of React for ProgrammersDavid Rodenas
 
Yearning jQuery
Yearning jQueryYearning jQuery
Yearning jQueryRemy Sharp
 
Asynchronous JS in Odoo
Asynchronous JS in OdooAsynchronous JS in Odoo
Asynchronous JS in OdooOdoo
 
Zf2 how arrays will save your project
Zf2   how arrays will save your projectZf2   how arrays will save your project
Zf2 how arrays will save your projectMichelangelo van Dam
 
Is HTML5 Ready? (workshop)
Is HTML5 Ready? (workshop)Is HTML5 Ready? (workshop)
Is HTML5 Ready? (workshop)Remy Sharp
 
The promise of asynchronous php
The promise of asynchronous phpThe promise of asynchronous php
The promise of asynchronous phpWim Godden
 
When dynamic becomes static: the next step in web caching techniques
When dynamic becomes static: the next step in web caching techniquesWhen dynamic becomes static: the next step in web caching techniques
When dynamic becomes static: the next step in web caching techniquesWim Godden
 
Introduction to ECMAScript 2015
Introduction to ECMAScript 2015Introduction to ECMAScript 2015
Introduction to ECMAScript 2015Tomasz Dziuda
 
Обзор фреймворка Twisted
Обзор фреймворка TwistedОбзор фреймворка Twisted
Обзор фреймворка TwistedMaxim Kulsha
 
OpenERP e l'arte della gestione aziendale con Python
OpenERP e l'arte della gestione aziendale con PythonOpenERP e l'arte della gestione aziendale con Python
OpenERP e l'arte della gestione aziendale con PythonPyCon Italia
 
Polymer - pleasant client-side programming with web components
Polymer - pleasant client-side programming with web componentsPolymer - pleasant client-side programming with web components
Polymer - pleasant client-side programming with web componentspsstoev
 
Essentials and Impactful Features of ES6
Essentials and Impactful Features of ES6Essentials and Impactful Features of ES6
Essentials and Impactful Features of ES6Riza Fahmi
 

What's hot (20)

My app is secure... I think
My app is secure... I thinkMy app is secure... I think
My app is secure... I think
 
My app is secure... I think
My app is secure... I thinkMy app is secure... I think
My app is secure... I think
 
jQuery Bay Area Conference 2010
jQuery Bay Area Conference 2010jQuery Bay Area Conference 2010
jQuery Bay Area Conference 2010
 
What's up with Prototype and script.aculo.us?
What's up with Prototype and script.aculo.us?What's up with Prototype and script.aculo.us?
What's up with Prototype and script.aculo.us?
 
Basic Tutorial of React for Programmers
Basic Tutorial of React for ProgrammersBasic Tutorial of React for Programmers
Basic Tutorial of React for Programmers
 
Yearning jQuery
Yearning jQueryYearning jQuery
Yearning jQuery
 
Asynchronous JS in Odoo
Asynchronous JS in OdooAsynchronous JS in Odoo
Asynchronous JS in Odoo
 
Zf2 how arrays will save your project
Zf2   how arrays will save your projectZf2   how arrays will save your project
Zf2 how arrays will save your project
 
QA for PHP projects
QA for PHP projectsQA for PHP projects
QA for PHP projects
 
Is HTML5 Ready? (workshop)
Is HTML5 Ready? (workshop)Is HTML5 Ready? (workshop)
Is HTML5 Ready? (workshop)
 
The promise of asynchronous php
The promise of asynchronous phpThe promise of asynchronous php
The promise of asynchronous php
 
Sane Async Patterns
Sane Async PatternsSane Async Patterns
Sane Async Patterns
 
Magic of Ruby
Magic of RubyMagic of Ruby
Magic of Ruby
 
When dynamic becomes static: the next step in web caching techniques
When dynamic becomes static: the next step in web caching techniquesWhen dynamic becomes static: the next step in web caching techniques
When dynamic becomes static: the next step in web caching techniques
 
Introduction to ECMAScript 2015
Introduction to ECMAScript 2015Introduction to ECMAScript 2015
Introduction to ECMAScript 2015
 
ES6 is Nigh
ES6 is NighES6 is Nigh
ES6 is Nigh
 
Обзор фреймворка Twisted
Обзор фреймворка TwistedОбзор фреймворка Twisted
Обзор фреймворка Twisted
 
OpenERP e l'arte della gestione aziendale con Python
OpenERP e l'arte della gestione aziendale con PythonOpenERP e l'arte della gestione aziendale con Python
OpenERP e l'arte della gestione aziendale con Python
 
Polymer - pleasant client-side programming with web components
Polymer - pleasant client-side programming with web componentsPolymer - pleasant client-side programming with web components
Polymer - pleasant client-side programming with web components
 
Essentials and Impactful Features of ES6
Essentials and Impactful Features of ES6Essentials and Impactful Features of ES6
Essentials and Impactful Features of ES6
 

Similar to Natural Task Scheduling Using Futures and Continuations, Ivan Čukić, Qt Developer Days 2013

Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...Domenic Denicola
 
EWD 3 Training Course Part 13: Putting Everything so far into Practice using ...
EWD 3 Training Course Part 13: Putting Everything so far into Practice using ...EWD 3 Training Course Part 13: Putting Everything so far into Practice using ...
EWD 3 Training Course Part 13: Putting Everything so far into Practice using ...Rob Tweed
 
Joe Bew - Apprendi un nuovo linguaggio sfruttando il TDD e il Clean Code - Co...
Joe Bew - Apprendi un nuovo linguaggio sfruttando il TDD e il Clean Code - Co...Joe Bew - Apprendi un nuovo linguaggio sfruttando il TDD e il Clean Code - Co...
Joe Bew - Apprendi un nuovo linguaggio sfruttando il TDD e il Clean Code - Co...Codemotion
 
Principles of the Play framework
Principles of the Play frameworkPrinciples of the Play framework
Principles of the Play frameworkBernhard Huemer
 
C-Sharp Arithmatic Expression Calculator
C-Sharp Arithmatic Expression CalculatorC-Sharp Arithmatic Expression Calculator
C-Sharp Arithmatic Expression CalculatorNeeraj Kaushik
 
Google App Engine Developer - Day3
Google App Engine Developer - Day3Google App Engine Developer - Day3
Google App Engine Developer - Day3Simon Su
 
How to build to do app using vue composition api and vuex 4 with typescript
How to build to do app using vue composition api and vuex 4 with typescriptHow to build to do app using vue composition api and vuex 4 with typescript
How to build to do app using vue composition api and vuex 4 with typescriptKaty Slemon
 
Progressive transpilation and the road to ES2015 in production
Progressive transpilation and the road to ES2015 in productionProgressive transpilation and the road to ES2015 in production
Progressive transpilation and the road to ES2015 in productionJacques Favreau
 
Working effectively with legacy code
Working effectively with legacy codeWorking effectively with legacy code
Working effectively with legacy codeShriKant Vashishtha
 
Orsiso
OrsisoOrsiso
Orsisoe27
 
J2ME Lwuit, Storage & Connections (Ft Prasanjit Dey)
J2ME Lwuit, Storage & Connections (Ft   Prasanjit Dey)J2ME Lwuit, Storage & Connections (Ft   Prasanjit Dey)
J2ME Lwuit, Storage & Connections (Ft Prasanjit Dey)Fafadia Tech
 
Avinash Kundaliya: Javascript and WordPress
Avinash Kundaliya: Javascript and WordPressAvinash Kundaliya: Javascript and WordPress
Avinash Kundaliya: Javascript and WordPresswpnepal
 
EWD 3 Training Course Part 43: Using JSON Web Tokens with QEWD REST Services
EWD 3 Training Course Part 43: Using JSON Web Tokens with QEWD REST ServicesEWD 3 Training Course Part 43: Using JSON Web Tokens with QEWD REST Services
EWD 3 Training Course Part 43: Using JSON Web Tokens with QEWD REST ServicesRob Tweed
 
Ecmascript 2015 – best of new features()
Ecmascript 2015 – best of new features()Ecmascript 2015 – best of new features()
Ecmascript 2015 – best of new features()Miłosz Sobczak
 
To Err Is Human
To Err Is HumanTo Err Is Human
To Err Is HumanAlex Liu
 
EWD 3 Training Course Part 11: Handling Errors in QEWD
EWD 3 Training Course Part 11: Handling Errors in QEWDEWD 3 Training Course Part 11: Handling Errors in QEWD
EWD 3 Training Course Part 11: Handling Errors in QEWDRob Tweed
 
Task Scheduling and Asynchronous Processing Evolved. Zend Server Job Queue
Task Scheduling and Asynchronous Processing Evolved. Zend Server Job QueueTask Scheduling and Asynchronous Processing Evolved. Zend Server Job Queue
Task Scheduling and Asynchronous Processing Evolved. Zend Server Job QueueSam Hennessy
 

Similar to Natural Task Scheduling Using Futures and Continuations, Ivan Čukić, Qt Developer Days 2013 (20)

Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
 
Celery
CeleryCelery
Celery
 
EWD 3 Training Course Part 13: Putting Everything so far into Practice using ...
EWD 3 Training Course Part 13: Putting Everything so far into Practice using ...EWD 3 Training Course Part 13: Putting Everything so far into Practice using ...
EWD 3 Training Course Part 13: Putting Everything so far into Practice using ...
 
Celery with python
Celery with pythonCelery with python
Celery with python
 
Joe Bew - Apprendi un nuovo linguaggio sfruttando il TDD e il Clean Code - Co...
Joe Bew - Apprendi un nuovo linguaggio sfruttando il TDD e il Clean Code - Co...Joe Bew - Apprendi un nuovo linguaggio sfruttando il TDD e il Clean Code - Co...
Joe Bew - Apprendi un nuovo linguaggio sfruttando il TDD e il Clean Code - Co...
 
Principles of the Play framework
Principles of the Play frameworkPrinciples of the Play framework
Principles of the Play framework
 
C-Sharp Arithmatic Expression Calculator
C-Sharp Arithmatic Expression CalculatorC-Sharp Arithmatic Expression Calculator
C-Sharp Arithmatic Expression Calculator
 
Google App Engine Developer - Day3
Google App Engine Developer - Day3Google App Engine Developer - Day3
Google App Engine Developer - Day3
 
ES6 Overview
ES6 OverviewES6 Overview
ES6 Overview
 
How to build to do app using vue composition api and vuex 4 with typescript
How to build to do app using vue composition api and vuex 4 with typescriptHow to build to do app using vue composition api and vuex 4 with typescript
How to build to do app using vue composition api and vuex 4 with typescript
 
Progressive transpilation and the road to ES2015 in production
Progressive transpilation and the road to ES2015 in productionProgressive transpilation and the road to ES2015 in production
Progressive transpilation and the road to ES2015 in production
 
Working effectively with legacy code
Working effectively with legacy codeWorking effectively with legacy code
Working effectively with legacy code
 
Orsiso
OrsisoOrsiso
Orsiso
 
J2ME Lwuit, Storage & Connections (Ft Prasanjit Dey)
J2ME Lwuit, Storage & Connections (Ft   Prasanjit Dey)J2ME Lwuit, Storage & Connections (Ft   Prasanjit Dey)
J2ME Lwuit, Storage & Connections (Ft Prasanjit Dey)
 
Avinash Kundaliya: Javascript and WordPress
Avinash Kundaliya: Javascript and WordPressAvinash Kundaliya: Javascript and WordPress
Avinash Kundaliya: Javascript and WordPress
 
EWD 3 Training Course Part 43: Using JSON Web Tokens with QEWD REST Services
EWD 3 Training Course Part 43: Using JSON Web Tokens with QEWD REST ServicesEWD 3 Training Course Part 43: Using JSON Web Tokens with QEWD REST Services
EWD 3 Training Course Part 43: Using JSON Web Tokens with QEWD REST Services
 
Ecmascript 2015 – best of new features()
Ecmascript 2015 – best of new features()Ecmascript 2015 – best of new features()
Ecmascript 2015 – best of new features()
 
To Err Is Human
To Err Is HumanTo Err Is Human
To Err Is Human
 
EWD 3 Training Course Part 11: Handling Errors in QEWD
EWD 3 Training Course Part 11: Handling Errors in QEWDEWD 3 Training Course Part 11: Handling Errors in QEWD
EWD 3 Training Course Part 11: Handling Errors in QEWD
 
Task Scheduling and Asynchronous Processing Evolved. Zend Server Job Queue
Task Scheduling and Asynchronous Processing Evolved. Zend Server Job QueueTask Scheduling and Asynchronous Processing Evolved. Zend Server Job Queue
Task Scheduling and Asynchronous Processing Evolved. Zend Server Job Queue
 

Recently uploaded

From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 

Recently uploaded (20)

From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 

Natural Task Scheduling Using Futures and Continuations, Ivan Čukić, Qt Developer Days 2013

  • 1. NATURAL TASK SCHEDULING Using Futures and Continuations Qt Developer Days 2013 Ivan Čukić ivan.cukic@kde.org ivan.fomentgroup.org/blog
  • 2. THE PROBLEM Meet Jeff Out of Control Reasons for Waiting
  • 3. The Problem Continuations Schedulers Tasks Epilogue MEET JEFF 3
  • 4. The Problem Continuations Schedulers Tasks Epilogue MEET JEFF void login() { user = get_username(); new_user = !check_if_user_exists(user); if (new_user) { pass = get_password(); initialize_account(uame, pass); } else do { pass = get_password(); } while (!check_user(user, pass)); initialize_environment(); if (new_user) show_welcome_message(); } 4
  • 5. The Problem Continuations Schedulers Tasks Epilogue MEET JEFF void login() { get_username(on_got_username); } void on_got_username( ::: ) { new_user = !check_if_user_exists(user); if (new_user) { get_password(on_got_password); } else { ::: } } void on_got_password( ::: ) { check_user(user, password, on_user_checked); } void on_user_checked( ::: ) { if (!user_valid) { on_got_username(user); } else { initialize_environment(on_environment_initialized); } } ::: 5
  • 6. The Problem Continuations Schedulers Tasks Epilogue OUT OF CONTROL 6
  • 7. The Problem Continuations Schedulers Tasks Epilogue OUT OF CONTROL “Spaghetti code” by George W. Hart 7
  • 8. The Problem Continuations Schedulers Tasks Epilogue REASONS FOR WAITING User input Network actions Inter-process communication External process execution Communication with a slow database CPU-intensive work Heterogeneous computing ... 8
  • 9. The Problem Continuations Schedulers Tasks Epilogue HIDEAWAY Wrapping it in task objects (QThread, KJob, ...) Methods with time-outs (select, ...) ... or with validity checks (QProcess::state, ...) Future values (future<T>, QFuture<T>, QDBusPendingReply<T>, ...) 9
  • 10. CONTINUATIONS Lost in the Future Under wraps
  • 11. The Problem Continuations Schedulers Tasks Epilogue LOST IN THE FUTURE Is it about monads? Callbacks? Signals and slots? 11
  • 12. The Problem Continuations Schedulers Tasks Epilogue LOST IN THE FUTURE C++ standard proposal N3558, Boost.Thread 1.55.0 future<int> result = deepThought.meaningOfLife(); #if 0 // this would block cout << result.get(); #endif result.then([] (future<int> result) { // called when the result is available // call to .get() does not block here cout << result.get(); }); 12
  • 13. The Problem Continuations Schedulers Tasks Epilogue LOST IN THE FUTURE | int i; | i.then(c); // ERROR! | future<int> future; | future.then(c); // ok | QFuture<int> qfuture; | qfuture.then(c); // ERROR! | | | | | | | | KJob *job; | job->then(c); // ERROR! | | | | | | 13
  • 14. The Problem Continuations Schedulers Tasks Epilogue LOST IN THE FUTURE | int i; | c(i); | future<int> future; | future.then(c); | QFuture<int> qfuture; | auto watcher = new QFutureWatcher<int>(); | QObject::connect(watcher, | &QFutureWatcherBase::finished, | [=] { | c(watcher->result()); | watcher->deleteLater(); | }); | watcher->setFuture(qfuture); | KJob *job; | QObject::connect(job, | &KJob::finished, | [] (KJob *job) { | c(job-> ... something ...); | job->deleteLater(); | }); | 14
  • 15. The Problem Continuations Schedulers Tasks Epilogue UNDER WRAPS template <typename _Job, typename _Continuation> void continue_with(_Job &&job, _Continuation &&continuation) { using is_nullary = typename std::is_constructible< std::function<void()>, _Continuation >::type; _continue_with_helper( job(), std::forward<_Continuation>(continuation), is_nullary() ); } 15
  • 16. The Problem Continuations Schedulers Tasks Epilogue UNDER WRAPS template <typename _ReturnType, typename _Continuation> void _continue_with_helper(const _ReturnType &value, _Continuation &&continuation, std::true_type) { continuation(); } template <typename _ReturnType, typename _Continuation> void _continue_with_helper(const _ReturnType &value, _Continuation &&continuation, std::false_type) { using is_callable = ...; static_assert(is_callable::value, "The continuation needs to have zero or one argument"); continuation(value); } 16
  • 17. The Problem Continuations Schedulers Tasks Epilogue UNDER WRAPS template <typename _ReturnType, typename _Continuation> void _continue_with_helper(const QFuture<_ReturnType> &future, _Continuation &&continuation, std::false_type) { if (!future.isFinished()) { auto watcher = new QFutureWatcher<_ReturnType>(); QObject::connect(watcher, &QFutureWatcherBase::finished, [=] { continuation(watcher->result()); watcher->deleteLater(); }); watcher->setFuture(future); } else continuation(future.result()); } 17
  • 18. The Problem Continuations Schedulers Tasks Epilogue MATCHBOX template<typename _TestType, typename _ArgType> class has_then_method { private: template<typename U, void (U::*)(_ArgType)> struct test_struct {}; template<typename U> static std::true_type test(test_struct <U, &U::then> *); template<typename U> static std::false_type test(...); public: using type = decltype(test<_TestType>(nullptr)); static const bool value = std::is_same<type, std::true_type>::value; } 18
  • 19. SCHEDULERS The Chains are On The New Order Set Your Controls for the Heart of the Sun
  • 20. The Problem Continuations Schedulers Tasks Epilogue THE CHAINS ARE ON getUsername().then( [] (future<string> username) { getPassword().then( [=] (future<string> password) { createAccount(username, password).then( ... ); } ); } ); Localized, but still not readable. Can it be made nicer? 20
  • 21. The Problem Continuations Schedulers Tasks Epilogue THE CHAINS ARE ON Can it be made to look like this? void login() { ... username = getUsername(); password = getPassword(); createAccount(username, password); } No, but ... 21
  • 22. The Problem Continuations Schedulers Tasks Epilogue THE CHAINS ARE ON ... it could look like this: auto login = serial_ ( ... username = getUsername(), password = getPassword(), createAccount(username, password) ); Peculiar syntax, but much more readable. 22
  • 23. The Problem Continuations Schedulers Tasks Epilogue THE NEW ORDER template <typename... _Jobs> class Serial; template <> class Serial<> : public QObject , protected QFutureInterface<int> { public: ~Serial() {} int operator()() { reportResult(0); reportFinished(); return 0; } }; 23
  • 24. The Problem Continuations Schedulers Tasks Epilogue THE NEW ORDER template <typename _Job, typename... _Jobs> class Serial<_Job, _Jobs...> : public Serial<_Jobs...> { private: using tail_t = Serial<_Jobs...>; public: Serial(_Job &&job, _Jobs &&... jobs) : tail_t(std::forward<_Jobs>(jobs)...) , m_job(std::forward<_Job>(job)) {} QFuture<int> operator()() { auto future = this->future(); continue_with(std::ref(m_job), [&] { tail_t::operator()(); }); return future; } private: _Job m_job; }; 24
  • 25. The Problem Continuations Schedulers Tasks Epilogue LET THERE BE MORE LIGHT while loop: while_( | while_(condition) ( condition, | body body | ) | ) branching: if_( | if_(condition) ( condition, | then_branch then_branch, | ).else_( else_branch | else_branch ) | ) 25
  • 26. The Problem Continuations Schedulers Tasks Epilogue LET THERE BE MORE LIGHT asynchronous assignment var<int> value; value = 5; // immediate assignment value = someFuture(); // asynchronous assignment parallel execution parallel_( task1, task2, ... ) parallel without waiting detach_(task) producer-consumer transactions ... 26
  • 27. The Problem Continuations Schedulers Tasks Epilogue SET YOUR CONTROLS... var<int> wait; serial_( test::writeMessage(0, "Starting the program"), wait = test::howMuchShouldIWait(7), test::writeMessageAsync(wait, "What is the answer to the Ultimate Question of Life, " "the Universe, and Everything?" ), while_(test::howMuchShouldIWait(0), test::writeMessageAsync(1, "42") ), serial_( test::writeMessageAsync(1, "We are going away..."), test::writeMessageAsync(1, "... sorry, but we have to.") ), test::writeMessage(0, "There, you have it!") )(); 27
  • 28. The Problem Continuations Schedulers Tasks Epilogue ... FOR THE HEART OF THE SUN while_( // Wait until we get a connection. client = ws::server::accept(server), // Start a detached execution path to process the client. detach_([] { var<ws::client_header> header; var<ws::message> message; var<string> server_key; serial_( // WebSocket handshake header = ws::client::get_header(), server_key = ws::server::create_key(header), ws::client::send_header(client, server_key), // Sending the initial greeting message ws::client::message_write(client, "Hello, I’m Echo"), // Connection established while_( // getting and echoing the message message = ws::client::message_read(client), ws::client::message_write(client, message) ) ) }) ) 28
  • 30. The Problem Continuations Schedulers Tasks Epilogue LAZY DAY Problem: A method is executed while the arguments are evaluated. serial_( someMethod(0, "Starting the program"), ... ); someMethod must not do anything, but return a functor. 30
  • 31. The Problem Continuations Schedulers Tasks Epilogue LAZY DAY So, your options are: void someMethod(...); serial_( std::bind(someMethod, 0, "Starting the program"), ... ) 31
  • 32. The Problem Continuations Schedulers Tasks Epilogue LAZY DAY Or using a std::bind-based wrapper namespace detail { void someMethod(...); } auto someMethod(...) -> decltype(std::bind(detail::someMethod, std::forward arguments ...)) { return std::bind(detail::someMethod, std::forward arguments ...); } serial_( someMethod(0, "Starting the program"), ... ) 32
  • 33. The Problem Continuations Schedulers Tasks Epilogue LAZY DAY Or using a simple wrapper: namespace detail { void someMethod(...); } auto someMethod = curry(detail::someMethod); serial_( someMethod(0, "Starting the program"), ... ) 33
  • 34. The Problem Continuations Schedulers Tasks Epilogue EPILOGUE Benefits: Readable code, easy to reason about Automatic lifetime management Advanced control structures compared to plain C++ Things to get used to: Peculiar syntax Some functional programming constructs like purity, immutability, etc. are preferred Less expressive statements 34
  • 35. The Problem Continuations Schedulers Tasks Epilogue ANSWERS? QUESTIONS! QUESTIONS? ANSWERS! Kudos: Friends at KDE Dr Saša Malkov KDAB basysKom LATEX and Beamer developers 35