SlideShare a Scribd company logo
1 of 14
Download to read offline
The Art of Concurrent
Programming
Past, Present and Future
Iskren Chernev
What is this talk about
● What is parallel, concurrent, asynchronous
● Brief history
● Run Loops
● Callbacks
● Promises
● Coroutines
Parallel, Concurrent, Asynchronous
● Parallel - 2 pieces of code running at the same time (threads/processes
running different CPUs, cores)
● Concurrent - the begining and end of 2 pieces of code overlap, but not
necessarily run at the same time (could be parralel, but not necessarily). So it
appears to overlap, but it doesn’t have to
● Asynchronous - an operation that will complete at a later time, but its
execution doesn’t block the thread/process
● We’ll cover Asynchronous programming in this lecture
Brief overview of the environment
● Obviously this talk is opinionated, so here’s what I have in mind
● server-side business logic applications
● little amount of computation
● A lot of IO (talking to other (micro)-services and databases)
● A huge volume of “easy” requests
● Client side is also mostly event driven with little computation so most of talk
applies there too
Brief History
● Single Threaded software
● Mutli-core brought with it Multi Threaded Software
○ (+) Its very close to single threaded software
○ (-) slow context switch, creation
○ (-) cache trashing
○ (-) need for synchronization primitives -- this is complicated
● With Node.js (2009) came the hype around asynchronous, single threaded
programming
● After that most other popular languages added asynchronous primitives and
libraries as standard, or popularized and extended existing asynchronous
primitives (Java, C#, Objective-C, Python)
So what is this Node.js all about
var server = http.createServer((request, response) => {
response.end( 'It Works!! Path Hit: ' + request.url);
})
server.listen(PORT, () => {
console.log("Server listening on: http://localhost:%s" , PORT);
})
Node.js - basic
function doSomethingSync(args) {
r = doSlow1(args);
return doSlow2(r)
}
function doSomething(args, done) {
doSlow1(args, (err, res) => {
if (err) return done(err);
doSlow2(res, done);
});
}
● Easy function creation with “closures” is a must
● Every async computation calls a given function after finished
What else - let’s try an if
function doSomethingSync(args) {
if (cond) {
r = doSlow1();
} else {
r = 5;
}
doFast(r);
return doSlow2();
}
WTF
function doSomething(args, done) {
var doRest = (r, done) => {
doFast(r)
doSlow2(done)
}
if (cond) {
return doSlow1((err, res) => {
if (err) return done(err)
doRest(arg, done)
})
}
doRest(5, done);
}
Key takeaways from Node.js
● Its great because it showed the world
what asynchronous code looks like and
how to do it with callbacks
● It sucks to actually code it (there is
async.js but its still pretty painful)
● Is here a better way?
● (pro) its very fast
● (pro) all libraries support callback async
interface
● (cons) writing correct async-callback
code is tricky to do right (easy to
double call the callback, or not call it at
all, or forget to return when calling done
● (cons) and its ugly (deep nesting for a
chain of async operations)
Run Loops
● Something like a thread manager
● Operations a run loop should implement
○ schedule(fn) -- this function only is enough
to implement basic concurrent systems
with multithreaded blocking IO (main
thread)
○ scheduleLater(when, fn) -- similar to
schedule but executes at a later point
○ addSocketWithEvents(sock, evmask, fn)
- register for socket events
○ NOTE: that linux support for async DISK io
is spotty, and is mostly wrapped with
thread pool under the hood
● Run loops are the basis of asynchronous
programming
● You can have one or many, and
communicate between them using
schedule
● Node.js has a run-loop built in, but other
languages added those later
● Libraries should explicitly support run
loops (if there are many), and most “old”
languages, “old” libraries are blocking
● You could shim any blocking operation
with a thread pool and a single main
run-loop
What is a Promise
● Called in different ways : Future,
CompletionStage (Java), Task (C#) etc
● Its an object representing the result of
an asynchronous operation
● It supports chaining
function doSomethingSync(args) {
if (cond) {
r = doSlow1();
} else {
r = 5;
}
doFast(r);
return doSlow2();
}
function doSomething(args) {
if (cond) {
r = doSlow1();
} else {
r = 5;
}
Promise.resole(r).then((r) => {
doFast(r);
return doSlow2();
});
}
Promises -- loops
function doSomethingConc(n) {
var futures = []
for (var i = 0; i < n; ++i) {
futures.push(doSlow(i));
}
// returns a new future, which
// resolves to an array of results
return Promise.all(futures);
}
function doSomethingSeries(n) {
var future = Promise.resolved(null);
var every = (i) => {
future = future.then(() => doSlow(i));
}
for (var i = 0; i < n; ++i) {
every(i);
}
return future;
}
Promisses - notes
● Error propagation
● If you need to exit early from a chain you have to use exceptions
● Compared to callbacks -- promisses guarantee listener is called at most once
● So callbacks are still necessary if you need to call listener many times
● In some languages (C++, some JS libs), promise and future are separate object
● In typed languages (C++, Java, C#) you need a few different APIs on the promise to handle async
and sync returns
● Normally the listener is called right after its produced, on the same thread, but you can change
that
● Promises are hard to implement -- use an official/stable lib, do NOT do it yourself
Coroutines
● Coroutines are mostly syntax sugar on top
of promises, but it pays off!
● The observation is that mostly you have a
linear chain of promises, so in that case
you can use a keyword await (C#, python)
/ yield (python)
● It handles linear code, ifs and serial
loops
● You can always fall back to promises if
what you’re doing is more complicated
(branches off, parralel loops)
● To implement you need support in the
language
async def doStuff(x):
if cond:
r = async doSlow(x)
else:
r = 5
doFast(r)
return async doSlow()

More Related Content

What's hot

Php under the_hood
Php under the_hoodPhp under the_hood
Php under the_hood
frank_neff
 
Node.js for Rubists
Node.js for RubistsNode.js for Rubists
Node.js for Rubists
Sagiv Ofek
 
HornetQ Presentation On JBoss World 2009
HornetQ Presentation On JBoss World 2009HornetQ Presentation On JBoss World 2009
HornetQ Presentation On JBoss World 2009
jarfield
 
Ruby projects of interest for DevOps
Ruby projects of interest for DevOpsRuby projects of interest for DevOps
Ruby projects of interest for DevOps
Ricardo Sanchez
 
From Test to Live with Rex
From Test to Live with RexFrom Test to Live with Rex
From Test to Live with Rex
Jan Gehring
 

What's hot (20)

Writing a fast HTTP parser
Writing a fast HTTP parserWriting a fast HTTP parser
Writing a fast HTTP parser
 
Introduction to ZeroMQ - eSpace TechTalk
Introduction to ZeroMQ - eSpace TechTalkIntroduction to ZeroMQ - eSpace TechTalk
Introduction to ZeroMQ - eSpace TechTalk
 
NullMQ @ PDX
NullMQ @ PDXNullMQ @ PDX
NullMQ @ PDX
 
Scalable Web Apps
Scalable Web AppsScalable Web Apps
Scalable Web Apps
 
Php under the_hood
Php under the_hoodPhp under the_hood
Php under the_hood
 
Blocks, procs && lambdas
Blocks, procs && lambdasBlocks, procs && lambdas
Blocks, procs && lambdas
 
Quick Introduction to Kotlin Coroutine for Android Dev
Quick Introduction to Kotlin Coroutine for Android DevQuick Introduction to Kotlin Coroutine for Android Dev
Quick Introduction to Kotlin Coroutine for Android Dev
 
Node.js for Rubists
Node.js for RubistsNode.js for Rubists
Node.js for Rubists
 
HornetQ Presentation On JBoss World 2009
HornetQ Presentation On JBoss World 2009HornetQ Presentation On JBoss World 2009
HornetQ Presentation On JBoss World 2009
 
Ruby projects of interest for DevOps
Ruby projects of interest for DevOpsRuby projects of interest for DevOps
Ruby projects of interest for DevOps
 
Zeromq anatomy & jeromq
Zeromq anatomy & jeromqZeromq anatomy & jeromq
Zeromq anatomy & jeromq
 
IPv4aaS tutorial and hands-on
IPv4aaS tutorial and hands-onIPv4aaS tutorial and hands-on
IPv4aaS tutorial and hands-on
 
Loom and concurrency latest
Loom and concurrency latestLoom and concurrency latest
Loom and concurrency latest
 
Overview of ZeroMQ
Overview of ZeroMQOverview of ZeroMQ
Overview of ZeroMQ
 
Kotlin Coroutines and Android sitting in a tree
Kotlin Coroutines and Android sitting in a treeKotlin Coroutines and Android sitting in a tree
Kotlin Coroutines and Android sitting in a tree
 
Practical SystemTAP basics: Perl memory profiling
Practical SystemTAP basics: Perl memory profilingPractical SystemTAP basics: Perl memory profiling
Practical SystemTAP basics: Perl memory profiling
 
From Test to Live with Rex
From Test to Live with RexFrom Test to Live with Rex
From Test to Live with Rex
 
Kotlin Coroutines and Android sitting in a tree - 2018 version
Kotlin Coroutines and Android sitting in a tree - 2018 versionKotlin Coroutines and Android sitting in a tree - 2018 version
Kotlin Coroutines and Android sitting in a tree - 2018 version
 
EhTrace -- RoP Hooks
EhTrace -- RoP HooksEhTrace -- RoP Hooks
EhTrace -- RoP Hooks
 
Dragoncraft Architectural Overview
Dragoncraft Architectural OverviewDragoncraft Architectural Overview
Dragoncraft Architectural Overview
 

Similar to The art of concurrent programming

Programming with Threads in Java
Programming with Threads in JavaProgramming with Threads in Java
Programming with Threads in Java
koji lin
 
The Evolution of Async-Programming on .NET Platform (.Net China, C#)
The Evolution of Async-Programming on .NET Platform (.Net China, C#)The Evolution of Async-Programming on .NET Platform (.Net China, C#)
The Evolution of Async-Programming on .NET Platform (.Net China, C#)
jeffz
 
Cassandra: Not Just NoSQL, It's MoSQL
Cassandra: Not Just NoSQL, It's MoSQLCassandra: Not Just NoSQL, It's MoSQL
Cassandra: Not Just NoSQL, It's MoSQL
Eric Evans
 
NoSQL Yes, But YesCQL, No?
NoSQL Yes, But YesCQL, No?NoSQL Yes, But YesCQL, No?
NoSQL Yes, But YesCQL, No?
Eric Evans
 
High-Performance Networking Using eBPF, XDP, and io_uring
High-Performance Networking Using eBPF, XDP, and io_uringHigh-Performance Networking Using eBPF, XDP, and io_uring
High-Performance Networking Using eBPF, XDP, and io_uring
ScyllaDB
 
Node js
Node jsNode js
Node js
hazzaz
 

Similar to The art of concurrent programming (20)

How NOT to write in Node.js
How NOT to write in Node.jsHow NOT to write in Node.js
How NOT to write in Node.js
 
Asynchronous Programming in .NET
Asynchronous Programming in .NETAsynchronous Programming in .NET
Asynchronous Programming in .NET
 
A first look into the Project Loom in Java
A first look into the Project Loom in JavaA first look into the Project Loom in Java
A first look into the Project Loom in Java
 
Programming with Threads in Java
Programming with Threads in JavaProgramming with Threads in Java
Programming with Threads in Java
 
PyCon Canada 2019 - Introduction to Asynchronous Programming
PyCon Canada 2019 - Introduction to Asynchronous ProgrammingPyCon Canada 2019 - Introduction to Asynchronous Programming
PyCon Canada 2019 - Introduction to Asynchronous Programming
 
Node.js Course 1 of 2 - Introduction and first steps
Node.js Course 1 of 2 - Introduction and first stepsNode.js Course 1 of 2 - Introduction and first steps
Node.js Course 1 of 2 - Introduction and first steps
 
The Evolution of Async-Programming on .NET Platform (.Net China, C#)
The Evolution of Async-Programming on .NET Platform (.Net China, C#)The Evolution of Async-Programming on .NET Platform (.Net China, C#)
The Evolution of Async-Programming on .NET Platform (.Net China, C#)
 
Asynchronous Python A Gentle Introduction
Asynchronous Python A Gentle IntroductionAsynchronous Python A Gentle Introduction
Asynchronous Python A Gentle Introduction
 
Let's Talk Locks!
Let's Talk Locks!Let's Talk Locks!
Let's Talk Locks!
 
Cassandra: Not Just NoSQL, It's MoSQL
Cassandra: Not Just NoSQL, It's MoSQLCassandra: Not Just NoSQL, It's MoSQL
Cassandra: Not Just NoSQL, It's MoSQL
 
NoSQL Yes, But YesCQL, No?
NoSQL Yes, But YesCQL, No?NoSQL Yes, But YesCQL, No?
NoSQL Yes, But YesCQL, No?
 
Introduction to Python Asyncio
Introduction to Python AsyncioIntroduction to Python Asyncio
Introduction to Python Asyncio
 
High-Performance Networking Using eBPF, XDP, and io_uring
High-Performance Networking Using eBPF, XDP, and io_uringHigh-Performance Networking Using eBPF, XDP, and io_uring
High-Performance Networking Using eBPF, XDP, and io_uring
 
Async programming and python
Async programming and pythonAsync programming and python
Async programming and python
 
Rust's Journey to Async/await
Rust's Journey to Async/awaitRust's Journey to Async/await
Rust's Journey to Async/await
 
epoll() - The I/O Hero
epoll() - The I/O Heroepoll() - The I/O Hero
epoll() - The I/O Hero
 
Node.js: CAMTA Presentation
Node.js: CAMTA PresentationNode.js: CAMTA Presentation
Node.js: CAMTA Presentation
 
Node js
Node jsNode js
Node js
 
Node.js streams talk
Node.js streams talkNode.js streams talk
Node.js streams talk
 
NodeJS
NodeJSNodeJS
NodeJS
 

Recently uploaded

CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
VishalKumarJha10
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
VictorSzoltysek
 

Recently uploaded (20)

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
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
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
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdf
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
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
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
 
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 ...
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
 

The art of concurrent programming

  • 1. The Art of Concurrent Programming Past, Present and Future Iskren Chernev
  • 2. What is this talk about ● What is parallel, concurrent, asynchronous ● Brief history ● Run Loops ● Callbacks ● Promises ● Coroutines
  • 3. Parallel, Concurrent, Asynchronous ● Parallel - 2 pieces of code running at the same time (threads/processes running different CPUs, cores) ● Concurrent - the begining and end of 2 pieces of code overlap, but not necessarily run at the same time (could be parralel, but not necessarily). So it appears to overlap, but it doesn’t have to ● Asynchronous - an operation that will complete at a later time, but its execution doesn’t block the thread/process ● We’ll cover Asynchronous programming in this lecture
  • 4. Brief overview of the environment ● Obviously this talk is opinionated, so here’s what I have in mind ● server-side business logic applications ● little amount of computation ● A lot of IO (talking to other (micro)-services and databases) ● A huge volume of “easy” requests ● Client side is also mostly event driven with little computation so most of talk applies there too
  • 5. Brief History ● Single Threaded software ● Mutli-core brought with it Multi Threaded Software ○ (+) Its very close to single threaded software ○ (-) slow context switch, creation ○ (-) cache trashing ○ (-) need for synchronization primitives -- this is complicated ● With Node.js (2009) came the hype around asynchronous, single threaded programming ● After that most other popular languages added asynchronous primitives and libraries as standard, or popularized and extended existing asynchronous primitives (Java, C#, Objective-C, Python)
  • 6. So what is this Node.js all about var server = http.createServer((request, response) => { response.end( 'It Works!! Path Hit: ' + request.url); }) server.listen(PORT, () => { console.log("Server listening on: http://localhost:%s" , PORT); })
  • 7. Node.js - basic function doSomethingSync(args) { r = doSlow1(args); return doSlow2(r) } function doSomething(args, done) { doSlow1(args, (err, res) => { if (err) return done(err); doSlow2(res, done); }); } ● Easy function creation with “closures” is a must ● Every async computation calls a given function after finished
  • 8. What else - let’s try an if function doSomethingSync(args) { if (cond) { r = doSlow1(); } else { r = 5; } doFast(r); return doSlow2(); } WTF function doSomething(args, done) { var doRest = (r, done) => { doFast(r) doSlow2(done) } if (cond) { return doSlow1((err, res) => { if (err) return done(err) doRest(arg, done) }) } doRest(5, done); }
  • 9. Key takeaways from Node.js ● Its great because it showed the world what asynchronous code looks like and how to do it with callbacks ● It sucks to actually code it (there is async.js but its still pretty painful) ● Is here a better way? ● (pro) its very fast ● (pro) all libraries support callback async interface ● (cons) writing correct async-callback code is tricky to do right (easy to double call the callback, or not call it at all, or forget to return when calling done ● (cons) and its ugly (deep nesting for a chain of async operations)
  • 10. Run Loops ● Something like a thread manager ● Operations a run loop should implement ○ schedule(fn) -- this function only is enough to implement basic concurrent systems with multithreaded blocking IO (main thread) ○ scheduleLater(when, fn) -- similar to schedule but executes at a later point ○ addSocketWithEvents(sock, evmask, fn) - register for socket events ○ NOTE: that linux support for async DISK io is spotty, and is mostly wrapped with thread pool under the hood ● Run loops are the basis of asynchronous programming ● You can have one or many, and communicate between them using schedule ● Node.js has a run-loop built in, but other languages added those later ● Libraries should explicitly support run loops (if there are many), and most “old” languages, “old” libraries are blocking ● You could shim any blocking operation with a thread pool and a single main run-loop
  • 11. What is a Promise ● Called in different ways : Future, CompletionStage (Java), Task (C#) etc ● Its an object representing the result of an asynchronous operation ● It supports chaining function doSomethingSync(args) { if (cond) { r = doSlow1(); } else { r = 5; } doFast(r); return doSlow2(); } function doSomething(args) { if (cond) { r = doSlow1(); } else { r = 5; } Promise.resole(r).then((r) => { doFast(r); return doSlow2(); }); }
  • 12. Promises -- loops function doSomethingConc(n) { var futures = [] for (var i = 0; i < n; ++i) { futures.push(doSlow(i)); } // returns a new future, which // resolves to an array of results return Promise.all(futures); } function doSomethingSeries(n) { var future = Promise.resolved(null); var every = (i) => { future = future.then(() => doSlow(i)); } for (var i = 0; i < n; ++i) { every(i); } return future; }
  • 13. Promisses - notes ● Error propagation ● If you need to exit early from a chain you have to use exceptions ● Compared to callbacks -- promisses guarantee listener is called at most once ● So callbacks are still necessary if you need to call listener many times ● In some languages (C++, some JS libs), promise and future are separate object ● In typed languages (C++, Java, C#) you need a few different APIs on the promise to handle async and sync returns ● Normally the listener is called right after its produced, on the same thread, but you can change that ● Promises are hard to implement -- use an official/stable lib, do NOT do it yourself
  • 14. Coroutines ● Coroutines are mostly syntax sugar on top of promises, but it pays off! ● The observation is that mostly you have a linear chain of promises, so in that case you can use a keyword await (C#, python) / yield (python) ● It handles linear code, ifs and serial loops ● You can always fall back to promises if what you’re doing is more complicated (branches off, parralel loops) ● To implement you need support in the language async def doStuff(x): if cond: r = async doSlow(x) else: r = 5 doFast(r) return async doSlow()