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

Writing a fast HTTP parser
Writing a fast HTTP parserWriting a fast HTTP parser
Writing a fast HTTP parserfukamachi
 
Introduction to ZeroMQ - eSpace TechTalk
Introduction to ZeroMQ - eSpace TechTalkIntroduction to ZeroMQ - eSpace TechTalk
Introduction to ZeroMQ - eSpace TechTalkMahmoud Said
 
Php under the_hood
Php under the_hoodPhp under the_hood
Php under the_hoodfrank_neff
 
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 DevShuhei Shogen
 
Node.js for Rubists
Node.js for RubistsNode.js for Rubists
Node.js for RubistsSagiv Ofek
 
HornetQ Presentation On JBoss World 2009
HornetQ Presentation On JBoss World 2009HornetQ Presentation On JBoss World 2009
HornetQ Presentation On JBoss World 2009jarfield
 
Ruby projects of interest for DevOps
Ruby projects of interest for DevOpsRuby projects of interest for DevOps
Ruby projects of interest for DevOpsRicardo Sanchez
 
Zeromq anatomy & jeromq
Zeromq anatomy & jeromqZeromq anatomy & jeromq
Zeromq anatomy & jeromqDongmin Yu
 
IPv4aaS tutorial and hands-on
IPv4aaS tutorial and hands-onIPv4aaS tutorial and hands-on
IPv4aaS tutorial and hands-onAPNIC
 
Overview of ZeroMQ
Overview of ZeroMQOverview of ZeroMQ
Overview of ZeroMQpieterh
 
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 treeKai Koenig
 
Practical SystemTAP basics: Perl memory profiling
Practical SystemTAP basics: Perl memory profilingPractical SystemTAP basics: Perl memory profiling
Practical SystemTAP basics: Perl memory profilingLubomir Rintel
 
From Test to Live with Rex
From Test to Live with RexFrom Test to Live with Rex
From Test to Live with RexJan Gehring
 
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 versionKai Koenig
 
Dragoncraft Architectural Overview
Dragoncraft Architectural OverviewDragoncraft Architectural Overview
Dragoncraft Architectural Overviewjessesanford
 

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

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.jsPiotr Pelczar
 
Asynchronous Programming in .NET
Asynchronous Programming in .NETAsynchronous Programming in .NET
Asynchronous Programming in .NETPierre-Luc Maheu
 
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 JavaLukas Steinbrecher
 
Programming with Threads in Java
Programming with Threads in JavaProgramming with Threads in Java
Programming with Threads in Javakoji lin
 
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 ProgrammingJuti Noppornpitak
 
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 stepsManuel Eusebio de Paz Carmona
 
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
 
Asynchronous Python A Gentle Introduction
Asynchronous Python A Gentle IntroductionAsynchronous Python A Gentle Introduction
Asynchronous Python A Gentle IntroductionPyData
 
Let's Talk Locks!
Let's Talk Locks!Let's Talk Locks!
Let's Talk Locks!C4Media
 
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 MoSQLEric Evans
 
NoSQL Yes, But YesCQL, No?
NoSQL Yes, But YesCQL, No?NoSQL Yes, But YesCQL, No?
NoSQL Yes, But YesCQL, No?Eric Evans
 
Introduction to Python Asyncio
Introduction to Python AsyncioIntroduction to Python Asyncio
Introduction to Python AsyncioNathan Van Gheem
 
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_uringScyllaDB
 
Async programming and python
Async programming and pythonAsync programming and python
Async programming and pythonChetan Giridhar
 
Rust's Journey to Async/await
Rust's Journey to Async/awaitRust's Journey to Async/await
Rust's Journey to Async/awaitC4Media
 
epoll() - The I/O Hero
epoll() - The I/O Heroepoll() - The I/O Hero
epoll() - The I/O HeroMohsin Hijazee
 
Node.js: CAMTA Presentation
Node.js: CAMTA PresentationNode.js: CAMTA Presentation
Node.js: CAMTA PresentationRob Tweed
 
Node js
Node jsNode js
Node jshazzaz
 
Node.js streams talk
Node.js streams talkNode.js streams talk
Node.js streams talkzladuric
 

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

Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commercemanigoyal112
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024StefanoLambiase
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Angel Borroy López
 
Machine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringMachine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringHironori Washizaki
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...OnePlan Solutions
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfAlina Yurenko
 
Salesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZSalesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZABSYZ Inc
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaHanief Utama
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...Technogeeks
 
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptxReal-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptxRTS corp
 
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxUI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxAndreas Kunz
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfDrew Moseley
 
Sending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdfSending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdf31events.com
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprisepreethippts
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...OnePlan Solutions
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based projectAnoyGreter
 
VK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web DevelopmentVK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web Developmentvyaparkranti
 

Recently uploaded (20)

Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commerce
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
 
Advantages of Odoo ERP 17 for Your Business
Advantages of Odoo ERP 17 for Your BusinessAdvantages of Odoo ERP 17 for Your Business
Advantages of Odoo ERP 17 for Your Business
 
Machine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringMachine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their Engineering
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
 
Salesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZSalesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZ
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief Utama
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...
 
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptxReal-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
 
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort ServiceHot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
 
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxUI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdf
 
Sending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdfSending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdf
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprise
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based project
 
VK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web DevelopmentVK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web Development
 

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()