SlideShare a Scribd company logo
1 of 60
Download to read offline
Reactive programming and Qt
Qt World Summit, Berlin 2015
Ivan ˇCuki´c
ivan.cukic@kde.org
http://cukic.co
Reactive Continuations Ranges Streams Epilogue
About me
KDE development
Talks and teaching
Functional programming enthusiast, but not a purist
2
Reactive Continuations Ranges Streams Epilogue
Disclaimer
Make your code readable. Pretend the next person
who looks at your code is a psychopath and they know
where you live.
Philip Wadler
3
Reactive Continuations Ranges Streams Epilogue
Disclaimer
The code snippets are optimized for presentation, it is not
production-ready code.
std namespace is omitted, value arguments used instead of const-refs or
forwarding refs, etc.
4
REACTIVE
Reactive Continuations Ranges Streams Epilogue
What is reactive?
We believe that a coherent approach to systems
architecture is needed, and we believe that all
necessary aspects are already recognised individually:
we want systems that are Responsive, Resilient, Elastic
and Message Driven. We call these Reactive Systems.
Systems built as Reactive Systems are more flexible,
loosely-coupled and scalable. This makes them easier
to develop and amenable to change. They are
significantly more tolerant of failure and when failure
does occur they meet it with elegance rather than
disaster. Reactive Systems are highly responsive, giving
users effective interactive feedback.
Reactive Manifesto 2.0
6
.
Reactive Continuations Ranges Streams Epilogue
What is reactive?
Showing a response to a stimulus
Oxford Dictionary
8
Reactive Continuations Ranges Streams Epilogue
What is reactive?
C: event call-backs
Java: event listeners
C++/Qt: signals and slots
even IO streams?
9
Reactive Continuations Ranges Streams Epilogue
What is reactive?
No shared state
Separate isolated components
Communication only through message passing
10
Reactive Continuations Ranges Streams Epilogue
Reactive programming
connect(mouse, SIGNAL(mouseMoved(int, int)),
widget, SLOT(resize(int, int)));
11
Reactive Continuations Ranges Streams Epilogue
Reactive programming
connect(mouse, SIGNAL(mouseMoved(int, int)),
widget, SLOT(setWidth(int)));
12
Reactive Continuations Ranges Streams Epilogue
Reactive programming
Rectangle {
width: mouse.x
height: mouse.y
}
MouseArea {
id: mouse
. . .
}
13
Reactive Continuations Ranges Streams Epilogue
Functional reactive programming
Rectangle {
width: Math.sin(mouse.x - mouse.width / 2)
height: Math.cos(mouse.y - mouse.height / 2)
}
MouseArea {
id: mouse
. . .
}
Connections {
. . .
}
14
Reactive Continuations Ranges Streams Epilogue
Functional reactive programming
Timer {
id: delayedStatusUpdate
interval: 1000
running: true
onTriggered: {
if (!hasBlahBlah) {
item.status = Core.PassiveStatus
return
}
item.status = enabled
? Core.PassiveStatus
: Core.ActiveStatus
}
}
15
Reactive Continuations Ranges Streams Epilogue
Stream processing
16
CONTINUATIONS
Reactive Continuations Ranges Streams Epilogue
Concurrency
Interactive systems
Threads
Multiple processes
Distributed systems
Note: "concurrency" will mean that different tasks are executed at
overlapping times.
18
Reactive Continuations Ranges Streams Epilogue
Plain threads are bad
A large fraction of the flaws in software development
are due to programmers not fully understanding all the
possible states their code may execute in. In a
multithreaded environment, the lack of understanding
and the resulting problems are greatly amplified,
almost to the point of panic if you are paying attention.
John Carmack
In-depth: Functional programming in C++
19
Reactive Continuations Ranges Streams Epilogue
Plain threads are bad
Threads are not composable
Parallelism can’t be ‘disabled’
Difficult to ensure balanced load manually
Hartmut Kaiser
Plain Threads are the GOTO of Today’s Computing
Meeting C++ 2014
20
Reactive Continuations Ranges Streams Epilogue
Plain synchronization primitives are bad
You will likely get it wrong
S.L.O.W. (starvation, latency, overhead, wait)
Sean Parent
Better Code: Concurrency
C++ Russia, 2015
21
Reactive Continuations Ranges Streams Epilogue
Amdahl’s Law
1
(1−P )+ P
N
22
Reactive Continuations Ranges Streams Epilogue
Locks are the main problem
The biggest of all the big problems with recursive mutexes is that
they encourage you to completely lose track of your locking scheme
and scope. This is deadly. Evil. It’s the "thread eater". You hold locks
for the absolutely shortest possible time. Period. Always. If you’re
calling something with a lock held simply because you don’t know it’s
held, or because you don’t know whether the callee needs the mutex,
then you’re holding it too long. You’re aiming a shotgun at your
application and pulling the trigger. You presumably started using
threads to get concurrency; but you’ve just PREVENTED concurrency.
I’ve often joked that instead of picking up Djikstra’s cute
acronym we should have called the basic synchronization
object "the bottleneck". Bottlenecks are useful at times,
sometimes indispensible – but they’re never GOOD.
David Butenhof
Re: recursive mutexes
23
Reactive Continuations Ranges Streams Epilogue
Futures
Futures should be the lowest level concurrency abstractions.
std::future
boost::future
QFuture
Folly Future
any continuation - *.then([] . . . )
24
Reactive Continuations Ranges Streams Epilogue
Future
T value = function();
future<T> value = function(); . . . ; value.get();)
25
Reactive Continuations Ranges Streams Epilogue
Future
future<T> value = function(); . . . ; value.get();
future<T2> value = function().then(continuation);
26
Reactive Continuations Ranges Streams Epilogue
Futures
page("http://qtworldsummit.com/").get()
.then(
[] (auto &&result) {
cout << result.headers();
}
)
27
Reactive Continuations Ranges Streams Epilogue
Futures
page("http://qtworldsummit.com/").get()
.then(
[] (auto &&result) {
cout << result.headers();
for (image: result.image_tags) {
image.get().then(
[] (auto &&image_result) {
// do something
// with image_result
}
);
}
}
)
28
Reactive Continuations Ranges Streams Epilogue
Imperative chaining of futures
result = get("http://qtworldsummit.com/"),
for_(image = result.image_tags) (
image_result = image.get(),
// do something with image_result
. . .
)
29
Reactive Continuations Ranges Streams Epilogue
Imperative chaining of futures
while_(
// Wait until we get a connection.
client = ws::server::accept(server),
// Start a detached execution path to process the client.
detach_([] {
. . .
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)
)
)
})
)
Check out "Monads in chains" from Meeting C++ 2014
30
RANGES
Reactive Continuations Ranges Streams Epilogue
Ranges in C++
vector<int> xs;
int sum = 0;
for (x: xs) {
sum += x;
}
return sum;
32
Reactive Continuations Ranges Streams Epilogue
Ranges in C++
return accumulate(
xs.cbegin(), xs.cend(),
0
);
33
Reactive Continuations Ranges Streams Epilogue
Ranges in C++
return accumulate(
xs.cbegin(), xs.cend(),
1,
_1 * _2
);
34
Reactive Continuations Ranges Streams Epilogue
Ranges in C++
How to do an aggregation on a transformed list?
vector<int> xs;
int sum = 0;
for (x: xs) {
sum += x * x;
}
return sum;
35
Reactive Continuations Ranges Streams Epilogue
Ranges in C++
How to do an aggregation on a transformed list?
sum $ map (λ x → x * x) xs
36
Reactive Continuations Ranges Streams Epilogue
Ranges in C++
How to do an aggregation on a transformed list?
vector<int> temp;
std::transform(
xs.cbegin(), xs.cend(),
std::back_inserter(temp),
_1 * _1
);
return std::accumulate(
temp.cbegin(),
temp.cend()
);
37
Reactive Continuations Ranges Streams Epilogue
Ranges in C++, boost.range, N4128
How to do an aggregation on a transformed list?
return accumulate(xs | transformed(_1 * _1));
38
Reactive Continuations Ranges Streams Epilogue
Example
transactions
| filter(Transactions::price() > 1000)
| groupBy(Transactions::customerId())
| sort(
Transactions::price().desc() |
Transactions::customerName()
);
39
Reactive Continuations Ranges Streams Epilogue
Example boilerplate
namespace Transactions {
struct Record {
int customerId;
. . .
};
DECL_COLUMN(customerId)
. . .
}
Column meta-type has all operators implemented, asc(),
desc(), etc.
40
STREAMS
Reactive Continuations Ranges Streams Epilogue
Anything you think that you could ever be
for (item: items) {
// do something
}
for_each(items, [] (item i) {
// do something
});
42
Reactive Continuations Ranges Streams Epilogue
Just passing our time
43
Reactive Continuations Ranges Streams Epilogue
Oh we’ll keep on trying
44
Reactive Continuations Ranges Streams Epilogue
Flow of information
45
Reactive Continuations Ranges Streams Epilogue
Through the eons, and on and on
Web server client connection requests
User interface events
Database access
I/O
Anything and everything
46
Reactive Continuations Ranges Streams Epilogue
Till the end of time
Message passing:
continuation!newClientMessage
Call-callback:
onNewMessage(continuation)
Signals-slots:
connect(socket, &Socket::newConnection,
receiver, &Receiver::continuation)
Any data collection:
for_each(xs, continuation)
47
Reactive Continuations Ranges Streams Epilogue
Stream transformation
Streams can only be transformed with algorithms that accept
input ranges, since we don’t have all the items. We don’t even
know when (if) they will end.
map, bind, filter, take, drop, etc.
48
Reactive Continuations Ranges Streams Epilogue
Stream transformation
49
Reactive Continuations Ranges Streams Epilogue
Map / Transform
We have a stream of 2D coordinates (mouse coordinates).
// Projecting on the x-axis
mouse_position >>=
map(λ point → (point.x, 0))
// Projecting on the y-axis
mouse_position >>=
map(λ point → (0, point.y))
50
Reactive Continuations Ranges Streams Epilogue
Implementation detail
namespace stream {
template <typename Stream, typename Cont>
auto operator >>= (Stream &&stream,
Cont &&cont)
{
return stream.then(cont);
}
template <typename Under>
auto make_stream(Under &&under);
}
51
Reactive Continuations Ranges Streams Epilogue
Map
template <typename Func, typename Cont>
struct map_cont {
map_cont(Func f, Cont c) : f(f), c(c) { }
template <typename InType>
void operator () (const InType &in) {
c(f(in));
}
Func f;
Cont c;
};
52
Reactive Continuations Ranges Streams Epilogue
Fork (or parallel), tee
tee(print) >>=
fork(
receiver1,
receiver2
)
53
Reactive Continuations Ranges Streams Epilogue
Fork (or parallel), tee
template <typename ... Conts>
struct fork_impl;
template <typename Cont, typename ... Conts>
struct fork_impl<Cont, Conts...>: fork_impl<Conts...>
{
using parent_type = fork_impl<Conts...>;
fork_impl(Cont c, Conts... cs)
: parent_type(cs...), c(c)
{ }
template <typename InType>
void operator() (const InType &in) {
c(in);
parent_type::operator()(in);
}
Cont c;
};
54
Reactive Continuations Ranges Streams Epilogue
Stateful function objects
class gravity_object {
public:
gravity_object() { }
template <typename Cont>
void then(Cont &&c) { _f = std::forward<Cont>(c); }
QPointF operator() (const QPointF &new_point) {
m_point.setX(m_point.x() * .99 + new_point.x() * .01);
m_point.setY(m_point.y() * .99 + new_point.y() * .01);
return m_point;
}
private:
std::function<void(QPointF)> _f;
QPointF m_point;
};
55
Reactive Continuations Ranges Streams Epilogue
Stateful function objects
56
Reactive Continuations Ranges Streams Epilogue
Filter
bool pointFilter(const QPointF &point) {
return int(point.y()) % 100 == 0;
}
events >>=
filter(predicate) >>=
. . .
57
Reactive Continuations Ranges Streams Epilogue
Flat map
template <typename Func, typename Cont>
struct flatmap_cont {
flatmap_cont(Func f, Cont c)
: f(f)
, c(c)
{
}
template <typename InType>
void operator () (const InType &in) {
boost::for_each(f(in), c);
}
Func f;
Cont c;
};
58
Reactive Continuations Ranges Streams Epilogue
Flat map
class more_precision {
public:
more_precision() { }
template <typename Cont>
void then(Cont &&c) { _f = std::forward<Cont>(c); }
std::vector<QPointF> operator() (const QPointF &new_point) {
std::vector<QPointF> result;
int stepX = (m_previous_point.x() < new_point.x()) ? 1 : -1;
for (int i = (int)m_previous_point.x(); i != (int)new_point.x(); i += stepX) {
result.emplace_back(i, m_previous_point.y());
}
int stepY = (m_previous_point.y() < new_point.y()) ? 1 : -1;
for (int i = (int)m_previous_point.y(); i != (int)new_point.y(); i += stepY) {
result.emplace_back(new_point.x(), i);
}
m_previous_point = new_point;
return result;
}
private:
std::function<void(QPointF)> _f;
QPointF m_previous_point;
};
59
Reactive Continuations Ranges Streams Epilogue
Answers? Questions! Questions? Answers!
Kudos:
Friends at KDE, Dr Saˇsa Malkov
Worth reading and watching:
Iterators Must Go, Andrei Alexandrescu
Value Semantics and Range Algorithms, Chandler Carruth
Systematic Error Handling in C++, Andrei Alexandrescu
Ranges proposal, Eric Niebler
Reactive manifesto, Books on Erlang or Scala/Akka
60

More Related Content

What's hot

The Unicorn Getting Interested in KDE
The Unicorn Getting Interested in KDEThe Unicorn Getting Interested in KDE
The Unicorn Getting Interested in KDEAndrey Karpov
 
Java - Concurrent programming - Thread's basics
Java - Concurrent programming - Thread's basicsJava - Concurrent programming - Thread's basics
Java - Concurrent programming - Thread's basicsRiccardo Cardin
 
The Newest in Session Types
The Newest in Session TypesThe Newest in Session Types
The Newest in Session TypesRoland Kuhn
 
Qt Framework Events Signals Threads
Qt Framework Events Signals ThreadsQt Framework Events Signals Threads
Qt Framework Events Signals ThreadsNeera Mital
 
Whats New in Visual Studio 2012 for C++ Developers
Whats New in Visual Studio 2012 for C++ DevelopersWhats New in Visual Studio 2012 for C++ Developers
Whats New in Visual Studio 2012 for C++ DevelopersRainer Stropek
 
Qt multi threads
Qt multi threadsQt multi threads
Qt multi threadsYnon Perek
 
L Fu - Dao: a novel programming language for bioinformatics
L Fu - Dao: a novel programming language for bioinformaticsL Fu - Dao: a novel programming language for bioinformatics
L Fu - Dao: a novel programming language for bioinformaticsJan Aerts
 
Tesseract. Recognizing Errors in Recognition Software
Tesseract. Recognizing Errors in Recognition SoftwareTesseract. Recognizing Errors in Recognition Software
Tesseract. Recognizing Errors in Recognition SoftwareAndrey Karpov
 
Behavioral Reflection
Behavioral ReflectionBehavioral Reflection
Behavioral ReflectionMarcus Denker
 
The free lunch is over
The free lunch is overThe free lunch is over
The free lunch is overThadeu Russo
 
Java Exception Handling, Assertions and Logging
Java Exception Handling, Assertions and LoggingJava Exception Handling, Assertions and Logging
Java Exception Handling, Assertions and LoggingRiccardo Cardin
 
Algorithm and Programming (Procedure and Function)
Algorithm and Programming (Procedure and Function)Algorithm and Programming (Procedure and Function)
Algorithm and Programming (Procedure and Function)Adam Mukharil Bachtiar
 
Java - Remote method invocation
Java - Remote method invocationJava - Remote method invocation
Java - Remote method invocationRiccardo Cardin
 
Aspect Mining for Large Systems
Aspect Mining for Large SystemsAspect Mining for Large Systems
Aspect Mining for Large SystemsThomas Zimmermann
 

What's hot (20)

The Unicorn Getting Interested in KDE
The Unicorn Getting Interested in KDEThe Unicorn Getting Interested in KDE
The Unicorn Getting Interested in KDE
 
GCC RTL and Machine Description
GCC RTL and Machine DescriptionGCC RTL and Machine Description
GCC RTL and Machine Description
 
Java - Concurrent programming - Thread's basics
Java - Concurrent programming - Thread's basicsJava - Concurrent programming - Thread's basics
Java - Concurrent programming - Thread's basics
 
The Newest in Session Types
The Newest in Session TypesThe Newest in Session Types
The Newest in Session Types
 
Qt Framework Events Signals Threads
Qt Framework Events Signals ThreadsQt Framework Events Signals Threads
Qt Framework Events Signals Threads
 
S emb t13-freertos
S emb t13-freertosS emb t13-freertos
S emb t13-freertos
 
Whats New in Visual Studio 2012 for C++ Developers
Whats New in Visual Studio 2012 for C++ DevelopersWhats New in Visual Studio 2012 for C++ Developers
Whats New in Visual Studio 2012 for C++ Developers
 
Qt multi threads
Qt multi threadsQt multi threads
Qt multi threads
 
L Fu - Dao: a novel programming language for bioinformatics
L Fu - Dao: a novel programming language for bioinformaticsL Fu - Dao: a novel programming language for bioinformatics
L Fu - Dao: a novel programming language for bioinformatics
 
Tesseract. Recognizing Errors in Recognition Software
Tesseract. Recognizing Errors in Recognition SoftwareTesseract. Recognizing Errors in Recognition Software
Tesseract. Recognizing Errors in Recognition Software
 
Syntutic
SyntuticSyntutic
Syntutic
 
Stoop 305-reflective programming5
Stoop 305-reflective programming5Stoop 305-reflective programming5
Stoop 305-reflective programming5
 
Behavioral Reflection
Behavioral ReflectionBehavioral Reflection
Behavioral Reflection
 
The free lunch is over
The free lunch is overThe free lunch is over
The free lunch is over
 
C++ Coroutines
C++ CoroutinesC++ Coroutines
C++ Coroutines
 
PVS-Studio in 2019
PVS-Studio in 2019PVS-Studio in 2019
PVS-Studio in 2019
 
Java Exception Handling, Assertions and Logging
Java Exception Handling, Assertions and LoggingJava Exception Handling, Assertions and Logging
Java Exception Handling, Assertions and Logging
 
Algorithm and Programming (Procedure and Function)
Algorithm and Programming (Procedure and Function)Algorithm and Programming (Procedure and Function)
Algorithm and Programming (Procedure and Function)
 
Java - Remote method invocation
Java - Remote method invocationJava - Remote method invocation
Java - Remote method invocation
 
Aspect Mining for Large Systems
Aspect Mining for Large SystemsAspect Mining for Large Systems
Aspect Mining for Large Systems
 

Viewers also liked

Natural Task Scheduling Using Futures and Continuations, Ivan Čukić, Qt Devel...
Natural Task Scheduling Using Futures and Continuations, Ivan Čukić, Qt Devel...Natural Task Scheduling Using Futures and Continuations, Ivan Čukić, Qt Devel...
Natural Task Scheduling Using Futures and Continuations, Ivan Čukić, Qt Devel...Ivan Čukić
 
Григорий Демченко, Универсальный адаптер
Григорий Демченко, Универсальный адаптерГригорий Демченко, Универсальный адаптер
Григорий Демченко, Универсальный адаптерSergey Platonov
 
Полухин Антон, Как делать не надо: C++ велосипедостроение для профессионалов
Полухин Антон, Как делать не надо: C++ велосипедостроение для профессионаловПолухин Антон, Как делать не надо: C++ велосипедостроение для профессионалов
Полухин Антон, Как делать не надо: C++ велосипедостроение для профессионаловSergey Platonov
 
Догнать и перегнать boost::lexical_cast
Догнать и перегнать boost::lexical_castДогнать и перегнать boost::lexical_cast
Догнать и перегнать boost::lexical_castRoman Orlov
 
Алексей Кутумов, C++ без исключений, часть 3
Алексей Кутумов,  C++ без исключений, часть 3Алексей Кутумов,  C++ без исключений, часть 3
Алексей Кутумов, C++ без исключений, часть 3Platonov Sergey
 
Фитнес для вашего кода: как держать его в форме
Фитнес для вашего кода: как держать его в формеФитнес для вашего кода: как держать его в форме
Фитнес для вашего кода: как держать его в формеIlia Shishkov
 
Evgeniy Muralev, Mark Vince, Working with the compiler, not against it
Evgeniy Muralev, Mark Vince, Working with the compiler, not against itEvgeniy Muralev, Mark Vince, Working with the compiler, not against it
Evgeniy Muralev, Mark Vince, Working with the compiler, not against itSergey Platonov
 
C++ Core Guidelines
C++ Core Guidelines C++ Core Guidelines
C++ Core Guidelines Sergey Zubkov
 
Starter kit del docente hi tech - v03
Starter kit del docente hi tech - v03Starter kit del docente hi tech - v03
Starter kit del docente hi tech - v03Michele Maffucci
 
ZeroFormatterに見るC#で最速のシリアライザを作成する100億の方法
ZeroFormatterに見るC#で最速のシリアライザを作成する100億の方法ZeroFormatterに見るC#で最速のシリアライザを作成する100億の方法
ZeroFormatterに見るC#で最速のシリアライザを作成する100億の方法Yoshifumi Kawai
 
Photon Server Deep Dive - PhotonWireの実装から見つめるPhotonServerの基礎と応用
Photon Server Deep Dive - PhotonWireの実装から見つめるPhotonServerの基礎と応用Photon Server Deep Dive - PhotonWireの実装から見つめるPhotonServerの基礎と応用
Photon Server Deep Dive - PhotonWireの実装から見つめるPhotonServerの基礎と応用Yoshifumi Kawai
 
What, Why, How Create OSS Libraries - 過去に制作した30のライブラリから見るC#コーディングテクニックと個人OSSの...
What, Why, How Create OSS Libraries - 過去に制作した30のライブラリから見るC#コーディングテクニックと個人OSSの...What, Why, How Create OSS Libraries - 過去に制作した30のライブラリから見るC#コーディングテクニックと個人OSSの...
What, Why, How Create OSS Libraries - 過去に制作した30のライブラリから見るC#コーディングテクニックと個人OSSの...Yoshifumi Kawai
 
RuntimeUnitTestToolkit for Unity
RuntimeUnitTestToolkit for UnityRuntimeUnitTestToolkit for Unity
RuntimeUnitTestToolkit for UnityYoshifumi Kawai
 
NextGen Server/Client Architecture - gRPC + Unity + C#
NextGen Server/Client Architecture - gRPC + Unity + C#NextGen Server/Client Architecture - gRPC + Unity + C#
NextGen Server/Client Architecture - gRPC + Unity + C#Yoshifumi Kawai
 
ZeroFormatter/MagicOnion - Fastest C# Serializer/gRPC based C# RPC
ZeroFormatter/MagicOnion - Fastest C# Serializer/gRPC based C# RPCZeroFormatter/MagicOnion - Fastest C# Serializer/gRPC based C# RPC
ZeroFormatter/MagicOnion - Fastest C# Serializer/gRPC based C# RPCYoshifumi Kawai
 

Viewers also liked (15)

Natural Task Scheduling Using Futures and Continuations, Ivan Čukić, Qt Devel...
Natural Task Scheduling Using Futures and Continuations, Ivan Čukić, Qt Devel...Natural Task Scheduling Using Futures and Continuations, Ivan Čukić, Qt Devel...
Natural Task Scheduling Using Futures and Continuations, Ivan Čukić, Qt Devel...
 
Григорий Демченко, Универсальный адаптер
Григорий Демченко, Универсальный адаптерГригорий Демченко, Универсальный адаптер
Григорий Демченко, Универсальный адаптер
 
Полухин Антон, Как делать не надо: C++ велосипедостроение для профессионалов
Полухин Антон, Как делать не надо: C++ велосипедостроение для профессионаловПолухин Антон, Как делать не надо: C++ велосипедостроение для профессионалов
Полухин Антон, Как делать не надо: C++ велосипедостроение для профессионалов
 
Догнать и перегнать boost::lexical_cast
Догнать и перегнать boost::lexical_castДогнать и перегнать boost::lexical_cast
Догнать и перегнать boost::lexical_cast
 
Алексей Кутумов, C++ без исключений, часть 3
Алексей Кутумов,  C++ без исключений, часть 3Алексей Кутумов,  C++ без исключений, часть 3
Алексей Кутумов, C++ без исключений, часть 3
 
Фитнес для вашего кода: как держать его в форме
Фитнес для вашего кода: как держать его в формеФитнес для вашего кода: как держать его в форме
Фитнес для вашего кода: как держать его в форме
 
Evgeniy Muralev, Mark Vince, Working with the compiler, not against it
Evgeniy Muralev, Mark Vince, Working with the compiler, not against itEvgeniy Muralev, Mark Vince, Working with the compiler, not against it
Evgeniy Muralev, Mark Vince, Working with the compiler, not against it
 
C++ Core Guidelines
C++ Core Guidelines C++ Core Guidelines
C++ Core Guidelines
 
Starter kit del docente hi tech - v03
Starter kit del docente hi tech - v03Starter kit del docente hi tech - v03
Starter kit del docente hi tech - v03
 
ZeroFormatterに見るC#で最速のシリアライザを作成する100億の方法
ZeroFormatterに見るC#で最速のシリアライザを作成する100億の方法ZeroFormatterに見るC#で最速のシリアライザを作成する100億の方法
ZeroFormatterに見るC#で最速のシリアライザを作成する100億の方法
 
Photon Server Deep Dive - PhotonWireの実装から見つめるPhotonServerの基礎と応用
Photon Server Deep Dive - PhotonWireの実装から見つめるPhotonServerの基礎と応用Photon Server Deep Dive - PhotonWireの実装から見つめるPhotonServerの基礎と応用
Photon Server Deep Dive - PhotonWireの実装から見つめるPhotonServerの基礎と応用
 
What, Why, How Create OSS Libraries - 過去に制作した30のライブラリから見るC#コーディングテクニックと個人OSSの...
What, Why, How Create OSS Libraries - 過去に制作した30のライブラリから見るC#コーディングテクニックと個人OSSの...What, Why, How Create OSS Libraries - 過去に制作した30のライブラリから見るC#コーディングテクニックと個人OSSの...
What, Why, How Create OSS Libraries - 過去に制作した30のライブラリから見るC#コーディングテクニックと個人OSSの...
 
RuntimeUnitTestToolkit for Unity
RuntimeUnitTestToolkit for UnityRuntimeUnitTestToolkit for Unity
RuntimeUnitTestToolkit for Unity
 
NextGen Server/Client Architecture - gRPC + Unity + C#
NextGen Server/Client Architecture - gRPC + Unity + C#NextGen Server/Client Architecture - gRPC + Unity + C#
NextGen Server/Client Architecture - gRPC + Unity + C#
 
ZeroFormatter/MagicOnion - Fastest C# Serializer/gRPC based C# RPC
ZeroFormatter/MagicOnion - Fastest C# Serializer/gRPC based C# RPCZeroFormatter/MagicOnion - Fastest C# Serializer/gRPC based C# RPC
ZeroFormatter/MagicOnion - Fastest C# Serializer/gRPC based C# RPC
 

Similar to Reactive programming and Qt - Stream processing

Cling the llvm based interpreter
Cling the llvm based interpreterCling the llvm based interpreter
Cling the llvm based interpreterRoberto Nogueira
 
Reactive Java: Promises and Streams with Reakt (JavaOne talk 2016)
Reactive Java: Promises and Streams with Reakt  (JavaOne talk 2016)Reactive Java: Promises and Streams with Reakt  (JavaOne talk 2016)
Reactive Java: Promises and Streams with Reakt (JavaOne talk 2016)Rick Hightower
 
Reactive Java: Promises and Streams with Reakt (JavaOne Talk 2016)
Reactive Java:  Promises and Streams with Reakt (JavaOne Talk 2016)Reactive Java:  Promises and Streams with Reakt (JavaOne Talk 2016)
Reactive Java: Promises and Streams with Reakt (JavaOne Talk 2016)Rick Hightower
 
Fuel Up JavaScript with Functional Programming
Fuel Up JavaScript with Functional ProgrammingFuel Up JavaScript with Functional Programming
Fuel Up JavaScript with Functional ProgrammingShine Xavier
 
Functional Programming With Scala
Functional Programming With ScalaFunctional Programming With Scala
Functional Programming With ScalaKnoldus Inc.
 
20160609 nike techtalks reactive applications tools of the trade
20160609 nike techtalks reactive applications   tools of the trade20160609 nike techtalks reactive applications   tools of the trade
20160609 nike techtalks reactive applications tools of the tradeshinolajla
 
Non-blocking synchronization — what is it and why we (don't?) need it
Non-blocking synchronization — what is it and why we (don't?) need itNon-blocking synchronization — what is it and why we (don't?) need it
Non-blocking synchronization — what is it and why we (don't?) need itAlexey Fyodorov
 
Compiler optimizations based on call-graph flattening
Compiler optimizations based on call-graph flatteningCompiler optimizations based on call-graph flattening
Compiler optimizations based on call-graph flatteningCAFxX
 
Demystifying Reactive Programming
Demystifying Reactive ProgrammingDemystifying Reactive Programming
Demystifying Reactive ProgrammingTom Bulatewicz, PhD
 
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]Chris Adamson
 
4Developers 2018: Ile (nie) wiesz o strukturach w .NET (Łukasz Pyrzyk)
4Developers 2018: Ile (nie) wiesz o strukturach w .NET (Łukasz Pyrzyk)4Developers 2018: Ile (nie) wiesz o strukturach w .NET (Łukasz Pyrzyk)
4Developers 2018: Ile (nie) wiesz o strukturach w .NET (Łukasz Pyrzyk)PROIDEA
 
Concurrency Constructs Overview
Concurrency Constructs OverviewConcurrency Constructs Overview
Concurrency Constructs Overviewstasimus
 
Reactive programming with examples
Reactive programming with examplesReactive programming with examples
Reactive programming with examplesPeter Lawrey
 
Building High-Performance Language Implementations With Low Effort
Building High-Performance Language Implementations With Low EffortBuilding High-Performance Language Implementations With Low Effort
Building High-Performance Language Implementations With Low EffortStefan Marr
 
ScalaDays 2013 Keynote Speech by Martin Odersky
ScalaDays 2013 Keynote Speech by Martin OderskyScalaDays 2013 Keynote Speech by Martin Odersky
ScalaDays 2013 Keynote Speech by Martin OderskyTypesafe
 
Qt everywhere a c++ abstraction platform
Qt everywhere   a c++ abstraction platformQt everywhere   a c++ abstraction platform
Qt everywhere a c++ abstraction platformDeveler S.r.l.
 
Kotlin Backend Development 6 Yrs Recap. The Good, the Bad and the Ugly
Kotlin Backend Development 6 Yrs Recap. The Good, the Bad and the UglyKotlin Backend Development 6 Yrs Recap. The Good, the Bad and the Ugly
Kotlin Backend Development 6 Yrs Recap. The Good, the Bad and the UglyHaim Yadid
 

Similar to Reactive programming and Qt - Stream processing (20)

Cling the llvm based interpreter
Cling the llvm based interpreterCling the llvm based interpreter
Cling the llvm based interpreter
 
Reactive Java: Promises and Streams with Reakt (JavaOne talk 2016)
Reactive Java: Promises and Streams with Reakt  (JavaOne talk 2016)Reactive Java: Promises and Streams with Reakt  (JavaOne talk 2016)
Reactive Java: Promises and Streams with Reakt (JavaOne talk 2016)
 
Reactive Java: Promises and Streams with Reakt (JavaOne Talk 2016)
Reactive Java:  Promises and Streams with Reakt (JavaOne Talk 2016)Reactive Java:  Promises and Streams with Reakt (JavaOne Talk 2016)
Reactive Java: Promises and Streams with Reakt (JavaOne Talk 2016)
 
Fuel Up JavaScript with Functional Programming
Fuel Up JavaScript with Functional ProgrammingFuel Up JavaScript with Functional Programming
Fuel Up JavaScript with Functional Programming
 
Functional Programming With Scala
Functional Programming With ScalaFunctional Programming With Scala
Functional Programming With Scala
 
20160609 nike techtalks reactive applications tools of the trade
20160609 nike techtalks reactive applications   tools of the trade20160609 nike techtalks reactive applications   tools of the trade
20160609 nike techtalks reactive applications tools of the trade
 
Non-blocking synchronization — what is it and why we (don't?) need it
Non-blocking synchronization — what is it and why we (don't?) need itNon-blocking synchronization — what is it and why we (don't?) need it
Non-blocking synchronization — what is it and why we (don't?) need it
 
Compiler optimizations based on call-graph flattening
Compiler optimizations based on call-graph flatteningCompiler optimizations based on call-graph flattening
Compiler optimizations based on call-graph flattening
 
Demystifying Reactive Programming
Demystifying Reactive ProgrammingDemystifying Reactive Programming
Demystifying Reactive Programming
 
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
 
4Developers 2018: Ile (nie) wiesz o strukturach w .NET (Łukasz Pyrzyk)
4Developers 2018: Ile (nie) wiesz o strukturach w .NET (Łukasz Pyrzyk)4Developers 2018: Ile (nie) wiesz o strukturach w .NET (Łukasz Pyrzyk)
4Developers 2018: Ile (nie) wiesz o strukturach w .NET (Łukasz Pyrzyk)
 
Concurrency Constructs Overview
Concurrency Constructs OverviewConcurrency Constructs Overview
Concurrency Constructs Overview
 
Reactive programming with examples
Reactive programming with examplesReactive programming with examples
Reactive programming with examples
 
Building High-Performance Language Implementations With Low Effort
Building High-Performance Language Implementations With Low EffortBuilding High-Performance Language Implementations With Low Effort
Building High-Performance Language Implementations With Low Effort
 
ScalaDays 2013 Keynote Speech by Martin Odersky
ScalaDays 2013 Keynote Speech by Martin OderskyScalaDays 2013 Keynote Speech by Martin Odersky
ScalaDays 2013 Keynote Speech by Martin Odersky
 
Devoxx
DevoxxDevoxx
Devoxx
 
Qt everywhere a c++ abstraction platform
Qt everywhere   a c++ abstraction platformQt everywhere   a c++ abstraction platform
Qt everywhere a c++ abstraction platform
 
DZone_RC_RxJS
DZone_RC_RxJSDZone_RC_RxJS
DZone_RC_RxJS
 
Kotlin Backend Development 6 Yrs Recap. The Good, the Bad and the Ugly
Kotlin Backend Development 6 Yrs Recap. The Good, the Bad and the UglyKotlin Backend Development 6 Yrs Recap. The Good, the Bad and the Ugly
Kotlin Backend Development 6 Yrs Recap. The Good, the Bad and the Ugly
 
What`s New in Java 8
What`s New in Java 8What`s New in Java 8
What`s New in Java 8
 

Recently uploaded

Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfkalichargn70th171
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️anilsa9823
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about usDynamic Netsoft
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number SystemsJheuzeDellosa
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 

Recently uploaded (20)

Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about us
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number Systems
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 

Reactive programming and Qt - Stream processing

  • 1. Reactive programming and Qt Qt World Summit, Berlin 2015 Ivan ˇCuki´c ivan.cukic@kde.org http://cukic.co
  • 2. Reactive Continuations Ranges Streams Epilogue About me KDE development Talks and teaching Functional programming enthusiast, but not a purist 2
  • 3. Reactive Continuations Ranges Streams Epilogue Disclaimer Make your code readable. Pretend the next person who looks at your code is a psychopath and they know where you live. Philip Wadler 3
  • 4. Reactive Continuations Ranges Streams Epilogue Disclaimer The code snippets are optimized for presentation, it is not production-ready code. std namespace is omitted, value arguments used instead of const-refs or forwarding refs, etc. 4
  • 6. Reactive Continuations Ranges Streams Epilogue What is reactive? We believe that a coherent approach to systems architecture is needed, and we believe that all necessary aspects are already recognised individually: we want systems that are Responsive, Resilient, Elastic and Message Driven. We call these Reactive Systems. Systems built as Reactive Systems are more flexible, loosely-coupled and scalable. This makes them easier to develop and amenable to change. They are significantly more tolerant of failure and when failure does occur they meet it with elegance rather than disaster. Reactive Systems are highly responsive, giving users effective interactive feedback. Reactive Manifesto 2.0 6
  • 7. .
  • 8. Reactive Continuations Ranges Streams Epilogue What is reactive? Showing a response to a stimulus Oxford Dictionary 8
  • 9. Reactive Continuations Ranges Streams Epilogue What is reactive? C: event call-backs Java: event listeners C++/Qt: signals and slots even IO streams? 9
  • 10. Reactive Continuations Ranges Streams Epilogue What is reactive? No shared state Separate isolated components Communication only through message passing 10
  • 11. Reactive Continuations Ranges Streams Epilogue Reactive programming connect(mouse, SIGNAL(mouseMoved(int, int)), widget, SLOT(resize(int, int))); 11
  • 12. Reactive Continuations Ranges Streams Epilogue Reactive programming connect(mouse, SIGNAL(mouseMoved(int, int)), widget, SLOT(setWidth(int))); 12
  • 13. Reactive Continuations Ranges Streams Epilogue Reactive programming Rectangle { width: mouse.x height: mouse.y } MouseArea { id: mouse . . . } 13
  • 14. Reactive Continuations Ranges Streams Epilogue Functional reactive programming Rectangle { width: Math.sin(mouse.x - mouse.width / 2) height: Math.cos(mouse.y - mouse.height / 2) } MouseArea { id: mouse . . . } Connections { . . . } 14
  • 15. Reactive Continuations Ranges Streams Epilogue Functional reactive programming Timer { id: delayedStatusUpdate interval: 1000 running: true onTriggered: { if (!hasBlahBlah) { item.status = Core.PassiveStatus return } item.status = enabled ? Core.PassiveStatus : Core.ActiveStatus } } 15
  • 16. Reactive Continuations Ranges Streams Epilogue Stream processing 16
  • 18. Reactive Continuations Ranges Streams Epilogue Concurrency Interactive systems Threads Multiple processes Distributed systems Note: "concurrency" will mean that different tasks are executed at overlapping times. 18
  • 19. Reactive Continuations Ranges Streams Epilogue Plain threads are bad A large fraction of the flaws in software development are due to programmers not fully understanding all the possible states their code may execute in. In a multithreaded environment, the lack of understanding and the resulting problems are greatly amplified, almost to the point of panic if you are paying attention. John Carmack In-depth: Functional programming in C++ 19
  • 20. Reactive Continuations Ranges Streams Epilogue Plain threads are bad Threads are not composable Parallelism can’t be ‘disabled’ Difficult to ensure balanced load manually Hartmut Kaiser Plain Threads are the GOTO of Today’s Computing Meeting C++ 2014 20
  • 21. Reactive Continuations Ranges Streams Epilogue Plain synchronization primitives are bad You will likely get it wrong S.L.O.W. (starvation, latency, overhead, wait) Sean Parent Better Code: Concurrency C++ Russia, 2015 21
  • 22. Reactive Continuations Ranges Streams Epilogue Amdahl’s Law 1 (1−P )+ P N 22
  • 23. Reactive Continuations Ranges Streams Epilogue Locks are the main problem The biggest of all the big problems with recursive mutexes is that they encourage you to completely lose track of your locking scheme and scope. This is deadly. Evil. It’s the "thread eater". You hold locks for the absolutely shortest possible time. Period. Always. If you’re calling something with a lock held simply because you don’t know it’s held, or because you don’t know whether the callee needs the mutex, then you’re holding it too long. You’re aiming a shotgun at your application and pulling the trigger. You presumably started using threads to get concurrency; but you’ve just PREVENTED concurrency. I’ve often joked that instead of picking up Djikstra’s cute acronym we should have called the basic synchronization object "the bottleneck". Bottlenecks are useful at times, sometimes indispensible – but they’re never GOOD. David Butenhof Re: recursive mutexes 23
  • 24. Reactive Continuations Ranges Streams Epilogue Futures Futures should be the lowest level concurrency abstractions. std::future boost::future QFuture Folly Future any continuation - *.then([] . . . ) 24
  • 25. Reactive Continuations Ranges Streams Epilogue Future T value = function(); future<T> value = function(); . . . ; value.get();) 25
  • 26. Reactive Continuations Ranges Streams Epilogue Future future<T> value = function(); . . . ; value.get(); future<T2> value = function().then(continuation); 26
  • 27. Reactive Continuations Ranges Streams Epilogue Futures page("http://qtworldsummit.com/").get() .then( [] (auto &&result) { cout << result.headers(); } ) 27
  • 28. Reactive Continuations Ranges Streams Epilogue Futures page("http://qtworldsummit.com/").get() .then( [] (auto &&result) { cout << result.headers(); for (image: result.image_tags) { image.get().then( [] (auto &&image_result) { // do something // with image_result } ); } } ) 28
  • 29. Reactive Continuations Ranges Streams Epilogue Imperative chaining of futures result = get("http://qtworldsummit.com/"), for_(image = result.image_tags) ( image_result = image.get(), // do something with image_result . . . ) 29
  • 30. Reactive Continuations Ranges Streams Epilogue Imperative chaining of futures while_( // Wait until we get a connection. client = ws::server::accept(server), // Start a detached execution path to process the client. detach_([] { . . . 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) ) ) }) ) Check out "Monads in chains" from Meeting C++ 2014 30
  • 32. Reactive Continuations Ranges Streams Epilogue Ranges in C++ vector<int> xs; int sum = 0; for (x: xs) { sum += x; } return sum; 32
  • 33. Reactive Continuations Ranges Streams Epilogue Ranges in C++ return accumulate( xs.cbegin(), xs.cend(), 0 ); 33
  • 34. Reactive Continuations Ranges Streams Epilogue Ranges in C++ return accumulate( xs.cbegin(), xs.cend(), 1, _1 * _2 ); 34
  • 35. Reactive Continuations Ranges Streams Epilogue Ranges in C++ How to do an aggregation on a transformed list? vector<int> xs; int sum = 0; for (x: xs) { sum += x * x; } return sum; 35
  • 36. Reactive Continuations Ranges Streams Epilogue Ranges in C++ How to do an aggregation on a transformed list? sum $ map (λ x → x * x) xs 36
  • 37. Reactive Continuations Ranges Streams Epilogue Ranges in C++ How to do an aggregation on a transformed list? vector<int> temp; std::transform( xs.cbegin(), xs.cend(), std::back_inserter(temp), _1 * _1 ); return std::accumulate( temp.cbegin(), temp.cend() ); 37
  • 38. Reactive Continuations Ranges Streams Epilogue Ranges in C++, boost.range, N4128 How to do an aggregation on a transformed list? return accumulate(xs | transformed(_1 * _1)); 38
  • 39. Reactive Continuations Ranges Streams Epilogue Example transactions | filter(Transactions::price() > 1000) | groupBy(Transactions::customerId()) | sort( Transactions::price().desc() | Transactions::customerName() ); 39
  • 40. Reactive Continuations Ranges Streams Epilogue Example boilerplate namespace Transactions { struct Record { int customerId; . . . }; DECL_COLUMN(customerId) . . . } Column meta-type has all operators implemented, asc(), desc(), etc. 40
  • 42. Reactive Continuations Ranges Streams Epilogue Anything you think that you could ever be for (item: items) { // do something } for_each(items, [] (item i) { // do something }); 42
  • 43. Reactive Continuations Ranges Streams Epilogue Just passing our time 43
  • 44. Reactive Continuations Ranges Streams Epilogue Oh we’ll keep on trying 44
  • 45. Reactive Continuations Ranges Streams Epilogue Flow of information 45
  • 46. Reactive Continuations Ranges Streams Epilogue Through the eons, and on and on Web server client connection requests User interface events Database access I/O Anything and everything 46
  • 47. Reactive Continuations Ranges Streams Epilogue Till the end of time Message passing: continuation!newClientMessage Call-callback: onNewMessage(continuation) Signals-slots: connect(socket, &Socket::newConnection, receiver, &Receiver::continuation) Any data collection: for_each(xs, continuation) 47
  • 48. Reactive Continuations Ranges Streams Epilogue Stream transformation Streams can only be transformed with algorithms that accept input ranges, since we don’t have all the items. We don’t even know when (if) they will end. map, bind, filter, take, drop, etc. 48
  • 49. Reactive Continuations Ranges Streams Epilogue Stream transformation 49
  • 50. Reactive Continuations Ranges Streams Epilogue Map / Transform We have a stream of 2D coordinates (mouse coordinates). // Projecting on the x-axis mouse_position >>= map(λ point → (point.x, 0)) // Projecting on the y-axis mouse_position >>= map(λ point → (0, point.y)) 50
  • 51. Reactive Continuations Ranges Streams Epilogue Implementation detail namespace stream { template <typename Stream, typename Cont> auto operator >>= (Stream &&stream, Cont &&cont) { return stream.then(cont); } template <typename Under> auto make_stream(Under &&under); } 51
  • 52. Reactive Continuations Ranges Streams Epilogue Map template <typename Func, typename Cont> struct map_cont { map_cont(Func f, Cont c) : f(f), c(c) { } template <typename InType> void operator () (const InType &in) { c(f(in)); } Func f; Cont c; }; 52
  • 53. Reactive Continuations Ranges Streams Epilogue Fork (or parallel), tee tee(print) >>= fork( receiver1, receiver2 ) 53
  • 54. Reactive Continuations Ranges Streams Epilogue Fork (or parallel), tee template <typename ... Conts> struct fork_impl; template <typename Cont, typename ... Conts> struct fork_impl<Cont, Conts...>: fork_impl<Conts...> { using parent_type = fork_impl<Conts...>; fork_impl(Cont c, Conts... cs) : parent_type(cs...), c(c) { } template <typename InType> void operator() (const InType &in) { c(in); parent_type::operator()(in); } Cont c; }; 54
  • 55. Reactive Continuations Ranges Streams Epilogue Stateful function objects class gravity_object { public: gravity_object() { } template <typename Cont> void then(Cont &&c) { _f = std::forward<Cont>(c); } QPointF operator() (const QPointF &new_point) { m_point.setX(m_point.x() * .99 + new_point.x() * .01); m_point.setY(m_point.y() * .99 + new_point.y() * .01); return m_point; } private: std::function<void(QPointF)> _f; QPointF m_point; }; 55
  • 56. Reactive Continuations Ranges Streams Epilogue Stateful function objects 56
  • 57. Reactive Continuations Ranges Streams Epilogue Filter bool pointFilter(const QPointF &point) { return int(point.y()) % 100 == 0; } events >>= filter(predicate) >>= . . . 57
  • 58. Reactive Continuations Ranges Streams Epilogue Flat map template <typename Func, typename Cont> struct flatmap_cont { flatmap_cont(Func f, Cont c) : f(f) , c(c) { } template <typename InType> void operator () (const InType &in) { boost::for_each(f(in), c); } Func f; Cont c; }; 58
  • 59. Reactive Continuations Ranges Streams Epilogue Flat map class more_precision { public: more_precision() { } template <typename Cont> void then(Cont &&c) { _f = std::forward<Cont>(c); } std::vector<QPointF> operator() (const QPointF &new_point) { std::vector<QPointF> result; int stepX = (m_previous_point.x() < new_point.x()) ? 1 : -1; for (int i = (int)m_previous_point.x(); i != (int)new_point.x(); i += stepX) { result.emplace_back(i, m_previous_point.y()); } int stepY = (m_previous_point.y() < new_point.y()) ? 1 : -1; for (int i = (int)m_previous_point.y(); i != (int)new_point.y(); i += stepY) { result.emplace_back(new_point.x(), i); } m_previous_point = new_point; return result; } private: std::function<void(QPointF)> _f; QPointF m_previous_point; }; 59
  • 60. Reactive Continuations Ranges Streams Epilogue Answers? Questions! Questions? Answers! Kudos: Friends at KDE, Dr Saˇsa Malkov Worth reading and watching: Iterators Must Go, Andrei Alexandrescu Value Semantics and Range Algorithms, Chandler Carruth Systematic Error Handling in C++, Andrei Alexandrescu Ranges proposal, Eric Niebler Reactive manifesto, Books on Erlang or Scala/Akka 60