SlideShare ist ein Scribd-Unternehmen logo
1 von 41
Timur Shemsedinov
PROFESSIONAL JS CONFERENCE 5-6 APRIL ‘19 KIEV, UKRAINE
Introduction to multithreading concurrent programming in
Node.js with worker_threads, SharedArrayBuffer and Atomics
Shared memory and
multithreading in Node.js
PROFESSIONAL JS CONFERENCE Shared memory and multithreading in Node.js
Process
- Separate memory
- Separate resources
- Separate environment
Process / Thread
Thread
- Shared memory space
- Shared resources
- Common environment
Memory mapped files
PROFESSIONAL JS CONFERENCE Shared memory and multithreading in Node.js
Node.js
- child_process
- cluster
- worker_threads
--experimental-worker
- Atomics
- SharedArrayBuffer
Node.js 10.5 ... 11.7
process
PROFESSIONAL JS CONFERENCE Shared memory and multithreading in Node.js
process
JavaScript
thread
V8 libuv
node.js
JavaScript
Shared memory and Message passing
thread
V8 libuv
node.js
JavaScript
thread
V8 libuv
node.js
IPC
PROFESSIONAL JS CONFERENCE Shared memory and multithreading in Node.js
Node.js: worker_threads
Not supported:
- process.abort()
- process.chdir(name)
- process.initgroups(...)
- trace_events module
- IPC from parent
- process.setegid(id)
- process.seteuid(id)
- process.setgid(id)
- process.setgroups(...)
- process.setuid(id)
PROFESSIONAL JS CONFERENCE Shared memory and multithreading in Node.js
Node.js: worker_threads
Read-only in Worker threads:
- process.env
- process.title
- process.umask([mask])
PROFESSIONAL JS CONFERENCE Shared memory and multithreading in Node.js
Node.js: worker_threads
Different behavior:
- process.exit([code]) stops thread not process
- process.memoryUsage() rss for entire process
- Each thread has an independent async_hooks
- Signals will not be delivered through process.on
PROFESSIONAL JS CONFERENCE Shared memory and multithreading in Node.js
Node.js: worker_threads API
const threads = require('worker_threads');
const { Worker, isMainThread } = threads;
if (isMainThread) {
const worker =
new Worker(__filename, { workerData: {} });
} else {
const { parentPort } = threads;
}
PROFESSIONAL JS CONFERENCE Shared memory and multithreading in Node.js
Node.js: MessagePort API
worker.on('message', (...args) => {});
worker.on('error', err => {});
worker.on('exit', code => {});
worker.postMessage('Hello there!');
parentPort.postMessage('Hello there!');
parentPort.on('message', (...args) => {});
PROFESSIONAL JS CONFERENCE Shared memory and multithreading in Node.js
class Point {
constructor(buffer, offset) {
this.data = new Int8Array(buffer, offset, 2);
}
get x() { return this.data[0]; }
set x(value) { this.data[0] = value; }
...
Wrap Shared Memory with OOP
PROFESSIONAL JS CONFERENCE Shared memory and multithreading in Node.js
const buffer = new SharedArrayBuffer(64);
const point = new Point(buffer, 4);
point.x += 10;
point.y = 7;
const { x } = point;
Wrap Shared Memory with OOP
PROFESSIONAL JS CONFERENCE Shared memory and multithreading in Node.js
- Parallel Programming
- Asynchronous Programming
- Actor Model
- Transactional Memory
- Coroutines
Concurrent Computing
PROFESSIONAL JS CONFERENCE Shared memory and multithreading in Node.js
Parallel Programming
- Race condition
- Critical section
- Deadlock
- Livelock
- Starvation
PROFESSIONAL JS CONFERENCE Shared memory and multithreading in Node.js
Int8Array, Uint8Array,
Int16Array, Uint16Array,
Int32Array, Uint32Array
Atomics and SharedArrayBuffer
PROFESSIONAL JS CONFERENCE Shared memory and multithreading in Node.js
prev = Atomics.add(array, index, value)
prev = Atomics.sub(array, index, value)
prev = Atomics.and(array, index, value)
prev = Atomics.or(array, index, value)
prev = Atomics.xor(array, index, value)
ES2017 Atomics
PROFESSIONAL JS CONFERENCE Shared memory and multithreading in Node.js
function add(array, index, value) {
1 const prev = array[index];
2 const sum = prev + value;
3 array[index] = sum;
4 return prev;
}
Atomics.add(array, index, value)
PROFESSIONAL JS CONFERENCE Shared memory and multithreading in Node.js
stored = Atomics.store(array, index, value)
value = Atomics.load(array, index)
prev = Atomics.exchange(array, index, value)
prev = Atomics.compareExchange(
array, index, expected, replacement
)
ES2017 Atomics (CAS)
PROFESSIONAL JS CONFERENCE Shared memory and multithreading in Node.js
woken = Atomics.notify(array, index, count)
res = Atomics.wait(array, index, value, [timeout])
res <"ok" | "not-equal" | "timed-out">
array <Int32Array>
ES2017 Atomics (notify/wait)
PROFESSIONAL JS CONFERENCE Shared memory and multithreading in Node.js
Synchronization primitives
- Semaphore
- BinarySemaphore
- CountingSemaphore
- Condition variable
- SpinLock
- Mutex
- TimedMutex
- SharedMutex
- RecursiveMutex
- Monitor
- Barrier
PROFESSIONAL JS CONFERENCE Shared memory and multithreading in Node.js
- thread safe data structures
- lock-free data structures
- wait-free algorithms
- conflict-free data structures
Parallel Solutions
PROFESSIONAL JS CONFERENCE Shared memory and multithreading in Node.js
class Mutex {
constructor(shared, offset = 0)
enter()
leave()
}
https://github.com/HowProgrammingWorks/Mutex
Mutex
PROFESSIONAL JS CONFERENCE Shared memory and multithreading in Node.js
mutex.enter();
// do something
// with shared resources
// or data structures
mutex.leave();
Mutex usage
PROFESSIONAL JS CONFERENCE Shared memory and multithreading in Node.js
constructor(shared, offset = 0) {
this.lock = new Int32Array(shared, offset, 1);
this.owner = false;
}
const threads = require('worker_threads');
const { workerData } = threads;
const mutex1 = new Mutex(workerData, offset);
Mutex constructor
PROFESSIONAL JS CONFERENCE Shared memory and multithreading in Node.js
enter() {
let prev = Atomics.exchange(this.lock, 0, LOCKED);
while (prev !== UNLOCKED) {
Atomics.wait(this.lock, 0, LOCKED);
prev = Atomics.exchange(this.lock, 0, LOCKED);
}
this.owner = true;
} Example: 6-blocking.js
Mutex.enter with Atomics.wait
PROFESSIONAL JS CONFERENCE Shared memory and multithreading in Node.js
leave() {
if (!this.owner) return;
Atomics.store(this.lock, 0, UNLOCKED);
Atomics.notify(this.lock, 0, 1);
this.owner = false;
}
Mutex.leave with Atomics.notify
PROFESSIONAL JS CONFERENCE Shared memory and multithreading in Node.js
mutex.enter(() => {
// do something
// with shared resources
// or data structures
mutex.leave();
});
Async Mutex usage
PROFESSIONAL JS CONFERENCE Shared memory and multithreading in Node.js
await mutex.enter();
// do something
// with shared resources
// or data structures
mutex.leave();
Async Mutex usage
PROFESSIONAL JS CONFERENCE Shared memory and multithreading in Node.js
enter() {
return new Promise(resolve => {
while (true) {
let prev = Atomics.exchange(this.lock, 0, LOCKED);
if (prev === UNLOCKED) break;
}
this.owner = true;
resolve();
});
}
Spinlock
PROFESSIONAL JS CONFERENCE Shared memory and multithreading in Node.js
enter() {
return new Promise(resolve => {
const tryEnter = () => {
let prev = Atomics.exchange(this.lock, 0, LOCKED);
if (prev === UNLOCKED) {
this.owner = true;
resolve();
} else {
setTimeout(tryEnter, 0);
}
};
tryEnter();
});
}
Spinlock with setTimeout
PROFESSIONAL JS CONFERENCE Shared memory and multithreading in Node.js
constructor(messagePort, shared, offset = 0) {
this.port = messagePort;
this.lock = new Int32Array(shared, offset, 1);
this.owner = false;
this.trying = false;
this.resolve = null;
if (messagePort) {
messagePort.on('message', kind => {
if (kind === 'leave' && this.trying) this.tryEnter();
});
} Example: 8-async.js
}
Asynchronous Mutex
PROFESSIONAL JS CONFERENCE Shared memory and multithreading in Node.js
enter() {
return new Promise(resolve => {
this.resolve = resolve;
this.trying = true;
this.tryEnter();
});
}
Asynchronous Mutex.enter
PROFESSIONAL JS CONFERENCE Shared memory and multithreading in Node.js
tryEnter() {
if (!this.resolve) return;
let prev = Atomics.exchange(this.lock, 0, LOCKED);
if (prev === UNLOCKED) {
this.owner = true;
this.trying = false;
this.resolve();
this.resolve = null;
}
}
Asynchronous Mutex.tryEnter
PROFESSIONAL JS CONFERENCE Shared memory and multithreading in Node.js
- Low-level structures
e.g. Register, Counter, Buffer, Array, Lists...
- Abstract structures
e.g. Queue, Graph, Polyline, etc.
- Subject-domain classes
e.g. Sensors, Payment, Biometric data, etc.
Thread safe data structures
PROFESSIONAL JS CONFERENCE Shared memory and multithreading in Node.js
locks.request('resource', opt, async lock => {
if (lock) {
// critical section for `resource`
// will be released after return
}
});
https://wicg.github.io/web-locks/
Web Locks API
PROFESSIONAL JS CONFERENCE Shared memory and multithreading in Node.js
- https://github.com/nodejs/node/issues/22702
Open
- https://github.com/nodejs/node/pull/22719
Closed
Web Locks for Node.js
PROFESSIONAL JS CONFERENCE Shared memory and multithreading in Node.js
- Web Locks requires memory + messaging
- Multiple locks.request() calls requires queue
- Mutex.queue: Array<Lock> // resource
- Lock { name, mode, callback } // request
- Need await locks.request()
- Options: { mode, ifAvailable, steal, signal }
Web Locks API Implementation
PROFESSIONAL JS CONFERENCE Shared memory and multithreading in Node.js
locks.request('resource', lock => new Promise(
(resolve, reject) => {
// you can store or pass resolve and
// reject here as callbacks
}
));
https://wicg.github.io/web-locks/
Web Locks: Promise or thenable
PROFESSIONAL JS CONFERENCE Shared memory and multithreading in Node.js
const controller = new AbortController();
setTimeout(() => controller.abort(), 200);
const { signal } = controller;
locks.request('resource', { signal }, async lock => {
// lock is held
}).catch(err => {
// err is AbortError
});
Web Locks: Abort
PROFESSIONAL JS CONFERENCE Shared memory and multithreading in Node.js
- Passing handles between workers
- Native add-ons (with certain conditions)
- Debug
- Experimental
https://github.com/nodejs/node/issues/22940
To be solved
PROFESSIONAL JS CONFERENCE Shared memory and multithreading in Node.js
https://github.com/HowProgrammingWorks/Semaphore
https://github.com/HowProgrammingWorks/Mutex
https://github.com/metarhia/metasync
https://wicg.github.io/web-locks
https://nodejs.org/api/worker_threads.html
https://developer.mozilla.org/en-US/docs/Web/
JavaScript/Reference/Global_Objects/Atomics
Links
PROFESSIONAL JS CONFERENCE Shared memory and multithreading in Node.js
https://github.com/tshemsedinov
https://www.youtube.com/TimurShemsedinov
timur.shemsedinov@gmail.com
Thanks

Weitere ähnliche Inhalte

Was ist angesagt?

スローダウン、ハングを一発解決 スレッドダンプはトラブルシューティングの味方 #wlstudy
スローダウン、ハングを一発解決 スレッドダンプはトラブルシューティングの味方 #wlstudyスローダウン、ハングを一発解決 スレッドダンプはトラブルシューティングの味方 #wlstudy
スローダウン、ハングを一発解決 スレッドダンプはトラブルシューティングの味方 #wlstudy
Yusuke Yamamoto
 
Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applications
Tom Croucher
 
Building servers with Node.js
Building servers with Node.jsBuilding servers with Node.js
Building servers with Node.js
ConFoo
 
Grand Central Dispatch
Grand Central DispatchGrand Central Dispatch
Grand Central Dispatch
cqtt191
 

Was ist angesagt? (20)

Node.js in 2021
Node.js in 2021Node.js in 2021
Node.js in 2021
 
Introduction Node.js
Introduction Node.jsIntroduction Node.js
Introduction Node.js
 
node.js: Javascript's in your backend
node.js: Javascript's in your backendnode.js: Javascript's in your backend
node.js: Javascript's in your backend
 
Node ppt
Node pptNode ppt
Node ppt
 
Nodejs presentation
Nodejs presentationNodejs presentation
Nodejs presentation
 
Blocks & GCD
Blocks & GCDBlocks & GCD
Blocks & GCD
 
Dragoncraft Architectural Overview
Dragoncraft Architectural OverviewDragoncraft Architectural Overview
Dragoncraft Architectural Overview
 
NodeJS for Beginner
NodeJS for BeginnerNodeJS for Beginner
NodeJS for Beginner
 
スローダウン、ハングを一発解決 スレッドダンプはトラブルシューティングの味方 #wlstudy
スローダウン、ハングを一発解決 スレッドダンプはトラブルシューティングの味方 #wlstudyスローダウン、ハングを一発解決 スレッドダンプはトラブルシューティングの味方 #wlstudy
スローダウン、ハングを一発解決 スレッドダンプはトラブルシューティングの味方 #wlstudy
 
Metarhia: Node.js Macht Frei
Metarhia: Node.js Macht FreiMetarhia: Node.js Macht Frei
Metarhia: Node.js Macht Frei
 
Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applications
 
Server Side Event Driven Programming
Server Side Event Driven ProgrammingServer Side Event Driven Programming
Server Side Event Driven Programming
 
Robust C++ Task Systems Through Compile-time Checks
Robust C++ Task Systems Through Compile-time ChecksRobust C++ Task Systems Through Compile-time Checks
Robust C++ Task Systems Through Compile-time Checks
 
Building servers with Node.js
Building servers with Node.jsBuilding servers with Node.js
Building servers with Node.js
 
Grand Central Dispatch
Grand Central DispatchGrand Central Dispatch
Grand Central Dispatch
 
High Performance Core Data
High Performance Core DataHigh Performance Core Data
High Performance Core Data
 
NodeJS Concurrency
NodeJS ConcurrencyNodeJS Concurrency
NodeJS Concurrency
 
How to Test Asynchronous Code (v2)
How to Test Asynchronous Code (v2)How to Test Asynchronous Code (v2)
How to Test Asynchronous Code (v2)
 
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
 
Non-blocking I/O, Event loops and node.js
Non-blocking I/O, Event loops and node.jsNon-blocking I/O, Event loops and node.js
Non-blocking I/O, Event loops and node.js
 

Ähnlich wie JS Fest 2019. Тимур Шемсединов. Разделяемая память в многопоточном Node.js

Full-Stack JavaScript with Node.js
Full-Stack JavaScript with Node.jsFull-Stack JavaScript with Node.js
Full-Stack JavaScript with Node.js
Michael Lehmann
 

Ähnlich wie JS Fest 2019. Тимур Шемсединов. Разделяемая память в многопоточном Node.js (20)

Shared memory and multithreading in Node.js - Timur Shemsedinov - JSFest'19
Shared memory and multithreading in Node.js - Timur Shemsedinov - JSFest'19Shared memory and multithreading in Node.js - Timur Shemsedinov - JSFest'19
Shared memory and multithreading in Node.js - Timur Shemsedinov - JSFest'19
 
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
 
Java и Linux — особенности эксплуатации / Алексей Рагозин (Дойче Банк)
Java и Linux — особенности эксплуатации / Алексей Рагозин (Дойче Банк)Java и Linux — особенности эксплуатации / Алексей Рагозин (Дойче Банк)
Java и Linux — особенности эксплуатации / Алексей Рагозин (Дойче Банк)
 
Top 30 Node.js interview questions
Top 30 Node.js interview questionsTop 30 Node.js interview questions
Top 30 Node.js interview questions
 
Nodejs Intro Part One
Nodejs Intro Part OneNodejs Intro Part One
Nodejs Intro Part One
 
Java 7 Whats New(), Whats Next() from Oredev
Java 7 Whats New(), Whats Next() from OredevJava 7 Whats New(), Whats Next() from Oredev
Java 7 Whats New(), Whats Next() from Oredev
 
Node.js Introduction
Node.js IntroductionNode.js Introduction
Node.js Introduction
 
NodeJS
NodeJSNodeJS
NodeJS
 
Introduction to Ecmascript - ES6
Introduction to Ecmascript - ES6Introduction to Ecmascript - ES6
Introduction to Ecmascript - ES6
 
Threads and Node.js
Threads and Node.jsThreads and Node.js
Threads and Node.js
 
Node.js on Azure
Node.js on AzureNode.js on Azure
Node.js on Azure
 
Intro to Node.js
Intro to Node.jsIntro to Node.js
Intro to Node.js
 
Javantura v2 - Replication with MongoDB - what could go wrong... - Philipp Krenn
Javantura v2 - Replication with MongoDB - what could go wrong... - Philipp KrennJavantura v2 - Replication with MongoDB - what could go wrong... - Philipp Krenn
Javantura v2 - Replication with MongoDB - what could go wrong... - Philipp Krenn
 
WiredTiger In-Memory vs WiredTiger B-Tree
WiredTiger In-Memory vs WiredTiger B-TreeWiredTiger In-Memory vs WiredTiger B-Tree
WiredTiger In-Memory vs WiredTiger B-Tree
 
Hidden pearls for High-Performance-Persistence
Hidden pearls for High-Performance-PersistenceHidden pearls for High-Performance-Persistence
Hidden pearls for High-Performance-Persistence
 
Layered Caching in OpenResty
Layered Caching in OpenRestyLayered Caching in OpenResty
Layered Caching in OpenResty
 
How to make a high-quality Node.js app, Nikita Galkin
How to make a high-quality Node.js app, Nikita GalkinHow to make a high-quality Node.js app, Nikita Galkin
How to make a high-quality Node.js app, Nikita Galkin
 
10 things i wish i'd known before using spark in production
10 things i wish i'd known before using spark in production10 things i wish i'd known before using spark in production
10 things i wish i'd known before using spark in production
 
Full-Stack JavaScript with Node.js
Full-Stack JavaScript with Node.jsFull-Stack JavaScript with Node.js
Full-Stack JavaScript with Node.js
 
Spark on Mesos-A Deep Dive-(Dean Wampler and Tim Chen, Typesafe and Mesosphere)
Spark on Mesos-A Deep Dive-(Dean Wampler and Tim Chen, Typesafe and Mesosphere)Spark on Mesos-A Deep Dive-(Dean Wampler and Tim Chen, Typesafe and Mesosphere)
Spark on Mesos-A Deep Dive-(Dean Wampler and Tim Chen, Typesafe and Mesosphere)
 

Mehr von JSFestUA

Mehr von JSFestUA (20)

JS Fest 2019/Autumn. Роман Савіцький. Webcomponents & lit-element in production
JS Fest 2019/Autumn. Роман Савіцький. Webcomponents & lit-element in productionJS Fest 2019/Autumn. Роман Савіцький. Webcomponents & lit-element in production
JS Fest 2019/Autumn. Роман Савіцький. Webcomponents & lit-element in production
 
JS Fest 2019/Autumn. Erick Wendel. 10 secrets to improve Javascript Performance
JS Fest 2019/Autumn. Erick Wendel. 10 secrets to improve Javascript PerformanceJS Fest 2019/Autumn. Erick Wendel. 10 secrets to improve Javascript Performance
JS Fest 2019/Autumn. Erick Wendel. 10 secrets to improve Javascript Performance
 
JS Fest 2019/Autumn. Alexandre Gomes. Embrace the "react fatigue"
JS Fest 2019/Autumn. Alexandre Gomes. Embrace the "react fatigue"JS Fest 2019/Autumn. Alexandre Gomes. Embrace the "react fatigue"
JS Fest 2019/Autumn. Alexandre Gomes. Embrace the "react fatigue"
 
JS Fest 2019/Autumn. Anton Cherednikov. Choreographic or orchestral architect...
JS Fest 2019/Autumn. Anton Cherednikov. Choreographic or orchestral architect...JS Fest 2019/Autumn. Anton Cherednikov. Choreographic or orchestral architect...
JS Fest 2019/Autumn. Anton Cherednikov. Choreographic or orchestral architect...
 
JS Fest 2019/Autumn. Adam Leos. So why do you need to know Algorithms and Dat...
JS Fest 2019/Autumn. Adam Leos. So why do you need to know Algorithms and Dat...JS Fest 2019/Autumn. Adam Leos. So why do you need to know Algorithms and Dat...
JS Fest 2019/Autumn. Adam Leos. So why do you need to know Algorithms and Dat...
 
JS Fest 2019/Autumn. Marko Letic. Saving the world with JavaScript: A Data Vi...
JS Fest 2019/Autumn. Marko Letic. Saving the world with JavaScript: A Data Vi...JS Fest 2019/Autumn. Marko Letic. Saving the world with JavaScript: A Data Vi...
JS Fest 2019/Autumn. Marko Letic. Saving the world with JavaScript: A Data Vi...
 
JS Fest 2019/Autumn. Александр Товмач. JAMstack
JS Fest 2019/Autumn. Александр Товмач. JAMstackJS Fest 2019/Autumn. Александр Товмач. JAMstack
JS Fest 2019/Autumn. Александр Товмач. JAMstack
 
JS Fest 2019/Autumn. Влад Федосов. Technology agnostic microservices at SPA f...
JS Fest 2019/Autumn. Влад Федосов. Technology agnostic microservices at SPA f...JS Fest 2019/Autumn. Влад Федосов. Technology agnostic microservices at SPA f...
JS Fest 2019/Autumn. Влад Федосов. Technology agnostic microservices at SPA f...
 
JS Fest 2019/Autumn. Дмитрий Жарков. Blockchainize your SPA or Integrate Java...
JS Fest 2019/Autumn. Дмитрий Жарков. Blockchainize your SPA or Integrate Java...JS Fest 2019/Autumn. Дмитрий Жарков. Blockchainize your SPA or Integrate Java...
JS Fest 2019/Autumn. Дмитрий Жарков. Blockchainize your SPA or Integrate Java...
 
JS Fest 2019/Autumn. Maciej Treder. Angular Schematics - Develop for developers
JS Fest 2019/Autumn. Maciej Treder. Angular Schematics - Develop for developersJS Fest 2019/Autumn. Maciej Treder. Angular Schematics - Develop for developers
JS Fest 2019/Autumn. Maciej Treder. Angular Schematics - Develop for developers
 
JS Fest 2019/Autumn. Kyle Boss. A Tinder Love Story: Create a Wordpress Blog ...
JS Fest 2019/Autumn. Kyle Boss. A Tinder Love Story: Create a Wordpress Blog ...JS Fest 2019/Autumn. Kyle Boss. A Tinder Love Story: Create a Wordpress Blog ...
JS Fest 2019/Autumn. Kyle Boss. A Tinder Love Story: Create a Wordpress Blog ...
 
JS Fest 2019/Autumn. Андрей Старовойт. Зачем нужен тип "true" в TypeScript?
JS Fest 2019/Autumn. Андрей Старовойт. Зачем нужен тип "true" в TypeScript?JS Fest 2019/Autumn. Андрей Старовойт. Зачем нужен тип "true" в TypeScript?
JS Fest 2019/Autumn. Андрей Старовойт. Зачем нужен тип "true" в TypeScript?
 
JS Fest 2019/Autumn. Eyal Eizenberg. Tipping the Scale
JS Fest 2019/Autumn. Eyal Eizenberg. Tipping the ScaleJS Fest 2019/Autumn. Eyal Eizenberg. Tipping the Scale
JS Fest 2019/Autumn. Eyal Eizenberg. Tipping the Scale
 
JS Fest 2019/Autumn. Sota Ohara. Сreate own server less CMS from scratch
JS Fest 2019/Autumn. Sota Ohara. Сreate own server less CMS from scratchJS Fest 2019/Autumn. Sota Ohara. Сreate own server less CMS from scratch
JS Fest 2019/Autumn. Sota Ohara. Сreate own server less CMS from scratch
 
JS Fest 2019/Autumn. Джордж Евтушенко. Как стать программистом, которого хотят
JS Fest 2019/Autumn. Джордж Евтушенко. Как стать программистом, которого хотятJS Fest 2019/Autumn. Джордж Евтушенко. Как стать программистом, которого хотят
JS Fest 2019/Autumn. Джордж Евтушенко. Как стать программистом, которого хотят
 
JS Fest 2019/Autumn. Алексей Орленко. Node.js N-API for Rust
JS Fest 2019/Autumn. Алексей Орленко. Node.js N-API for RustJS Fest 2019/Autumn. Алексей Орленко. Node.js N-API for Rust
JS Fest 2019/Autumn. Алексей Орленко. Node.js N-API for Rust
 
JS Fest 2019/Autumn. Daniel Ostrovsky. Falling in love with decorators ES6/Ty...
JS Fest 2019/Autumn. Daniel Ostrovsky. Falling in love with decorators ES6/Ty...JS Fest 2019/Autumn. Daniel Ostrovsky. Falling in love with decorators ES6/Ty...
JS Fest 2019/Autumn. Daniel Ostrovsky. Falling in love with decorators ES6/Ty...
 
JS Fest 2019/Autumn. Андрей Андрийко. Гексагональна архітектура в Nodejs проекті
JS Fest 2019/Autumn. Андрей Андрийко. Гексагональна архітектура в Nodejs проектіJS Fest 2019/Autumn. Андрей Андрийко. Гексагональна архітектура в Nodejs проекті
JS Fest 2019/Autumn. Андрей Андрийко. Гексагональна архітектура в Nodejs проекті
 
JS Fest 2019/Autumn. Борис Могила. Svelte. Почему нам не нужно run-time ядро
JS Fest 2019/Autumn. Борис Могила. Svelte. Почему нам не нужно run-time ядроJS Fest 2019/Autumn. Борис Могила. Svelte. Почему нам не нужно run-time ядро
JS Fest 2019/Autumn. Борис Могила. Svelte. Почему нам не нужно run-time ядро
 
JS Fest 2019/Autumn. Виталий Кухар. Сравнение кластеризации HTTP, TCP и UDP н...
JS Fest 2019/Autumn. Виталий Кухар. Сравнение кластеризации HTTP, TCP и UDP н...JS Fest 2019/Autumn. Виталий Кухар. Сравнение кластеризации HTTP, TCP и UDP н...
JS Fest 2019/Autumn. Виталий Кухар. Сравнение кластеризации HTTP, TCP и UDP н...
 

Kürzlich hochgeladen

Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
ZurliaSoop
 

Kürzlich hochgeladen (20)

Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdf
 
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptxOn_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptx
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - English
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptx
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentation
 
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptx
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptx
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptx
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 

JS Fest 2019. Тимур Шемсединов. Разделяемая память в многопоточном Node.js

  • 1. Timur Shemsedinov PROFESSIONAL JS CONFERENCE 5-6 APRIL ‘19 KIEV, UKRAINE Introduction to multithreading concurrent programming in Node.js with worker_threads, SharedArrayBuffer and Atomics Shared memory and multithreading in Node.js
  • 2. PROFESSIONAL JS CONFERENCE Shared memory and multithreading in Node.js Process - Separate memory - Separate resources - Separate environment Process / Thread Thread - Shared memory space - Shared resources - Common environment Memory mapped files
  • 3. PROFESSIONAL JS CONFERENCE Shared memory and multithreading in Node.js Node.js - child_process - cluster - worker_threads --experimental-worker - Atomics - SharedArrayBuffer Node.js 10.5 ... 11.7
  • 4. process PROFESSIONAL JS CONFERENCE Shared memory and multithreading in Node.js process JavaScript thread V8 libuv node.js JavaScript Shared memory and Message passing thread V8 libuv node.js JavaScript thread V8 libuv node.js IPC
  • 5. PROFESSIONAL JS CONFERENCE Shared memory and multithreading in Node.js Node.js: worker_threads Not supported: - process.abort() - process.chdir(name) - process.initgroups(...) - trace_events module - IPC from parent - process.setegid(id) - process.seteuid(id) - process.setgid(id) - process.setgroups(...) - process.setuid(id)
  • 6. PROFESSIONAL JS CONFERENCE Shared memory and multithreading in Node.js Node.js: worker_threads Read-only in Worker threads: - process.env - process.title - process.umask([mask])
  • 7. PROFESSIONAL JS CONFERENCE Shared memory and multithreading in Node.js Node.js: worker_threads Different behavior: - process.exit([code]) stops thread not process - process.memoryUsage() rss for entire process - Each thread has an independent async_hooks - Signals will not be delivered through process.on
  • 8. PROFESSIONAL JS CONFERENCE Shared memory and multithreading in Node.js Node.js: worker_threads API const threads = require('worker_threads'); const { Worker, isMainThread } = threads; if (isMainThread) { const worker = new Worker(__filename, { workerData: {} }); } else { const { parentPort } = threads; }
  • 9. PROFESSIONAL JS CONFERENCE Shared memory and multithreading in Node.js Node.js: MessagePort API worker.on('message', (...args) => {}); worker.on('error', err => {}); worker.on('exit', code => {}); worker.postMessage('Hello there!'); parentPort.postMessage('Hello there!'); parentPort.on('message', (...args) => {});
  • 10. PROFESSIONAL JS CONFERENCE Shared memory and multithreading in Node.js class Point { constructor(buffer, offset) { this.data = new Int8Array(buffer, offset, 2); } get x() { return this.data[0]; } set x(value) { this.data[0] = value; } ... Wrap Shared Memory with OOP
  • 11. PROFESSIONAL JS CONFERENCE Shared memory and multithreading in Node.js const buffer = new SharedArrayBuffer(64); const point = new Point(buffer, 4); point.x += 10; point.y = 7; const { x } = point; Wrap Shared Memory with OOP
  • 12. PROFESSIONAL JS CONFERENCE Shared memory and multithreading in Node.js - Parallel Programming - Asynchronous Programming - Actor Model - Transactional Memory - Coroutines Concurrent Computing
  • 13. PROFESSIONAL JS CONFERENCE Shared memory and multithreading in Node.js Parallel Programming - Race condition - Critical section - Deadlock - Livelock - Starvation
  • 14. PROFESSIONAL JS CONFERENCE Shared memory and multithreading in Node.js Int8Array, Uint8Array, Int16Array, Uint16Array, Int32Array, Uint32Array Atomics and SharedArrayBuffer
  • 15. PROFESSIONAL JS CONFERENCE Shared memory and multithreading in Node.js prev = Atomics.add(array, index, value) prev = Atomics.sub(array, index, value) prev = Atomics.and(array, index, value) prev = Atomics.or(array, index, value) prev = Atomics.xor(array, index, value) ES2017 Atomics
  • 16. PROFESSIONAL JS CONFERENCE Shared memory and multithreading in Node.js function add(array, index, value) { 1 const prev = array[index]; 2 const sum = prev + value; 3 array[index] = sum; 4 return prev; } Atomics.add(array, index, value)
  • 17. PROFESSIONAL JS CONFERENCE Shared memory and multithreading in Node.js stored = Atomics.store(array, index, value) value = Atomics.load(array, index) prev = Atomics.exchange(array, index, value) prev = Atomics.compareExchange( array, index, expected, replacement ) ES2017 Atomics (CAS)
  • 18. PROFESSIONAL JS CONFERENCE Shared memory and multithreading in Node.js woken = Atomics.notify(array, index, count) res = Atomics.wait(array, index, value, [timeout]) res <"ok" | "not-equal" | "timed-out"> array <Int32Array> ES2017 Atomics (notify/wait)
  • 19. PROFESSIONAL JS CONFERENCE Shared memory and multithreading in Node.js Synchronization primitives - Semaphore - BinarySemaphore - CountingSemaphore - Condition variable - SpinLock - Mutex - TimedMutex - SharedMutex - RecursiveMutex - Monitor - Barrier
  • 20. PROFESSIONAL JS CONFERENCE Shared memory and multithreading in Node.js - thread safe data structures - lock-free data structures - wait-free algorithms - conflict-free data structures Parallel Solutions
  • 21. PROFESSIONAL JS CONFERENCE Shared memory and multithreading in Node.js class Mutex { constructor(shared, offset = 0) enter() leave() } https://github.com/HowProgrammingWorks/Mutex Mutex
  • 22. PROFESSIONAL JS CONFERENCE Shared memory and multithreading in Node.js mutex.enter(); // do something // with shared resources // or data structures mutex.leave(); Mutex usage
  • 23. PROFESSIONAL JS CONFERENCE Shared memory and multithreading in Node.js constructor(shared, offset = 0) { this.lock = new Int32Array(shared, offset, 1); this.owner = false; } const threads = require('worker_threads'); const { workerData } = threads; const mutex1 = new Mutex(workerData, offset); Mutex constructor
  • 24. PROFESSIONAL JS CONFERENCE Shared memory and multithreading in Node.js enter() { let prev = Atomics.exchange(this.lock, 0, LOCKED); while (prev !== UNLOCKED) { Atomics.wait(this.lock, 0, LOCKED); prev = Atomics.exchange(this.lock, 0, LOCKED); } this.owner = true; } Example: 6-blocking.js Mutex.enter with Atomics.wait
  • 25. PROFESSIONAL JS CONFERENCE Shared memory and multithreading in Node.js leave() { if (!this.owner) return; Atomics.store(this.lock, 0, UNLOCKED); Atomics.notify(this.lock, 0, 1); this.owner = false; } Mutex.leave with Atomics.notify
  • 26. PROFESSIONAL JS CONFERENCE Shared memory and multithreading in Node.js mutex.enter(() => { // do something // with shared resources // or data structures mutex.leave(); }); Async Mutex usage
  • 27. PROFESSIONAL JS CONFERENCE Shared memory and multithreading in Node.js await mutex.enter(); // do something // with shared resources // or data structures mutex.leave(); Async Mutex usage
  • 28. PROFESSIONAL JS CONFERENCE Shared memory and multithreading in Node.js enter() { return new Promise(resolve => { while (true) { let prev = Atomics.exchange(this.lock, 0, LOCKED); if (prev === UNLOCKED) break; } this.owner = true; resolve(); }); } Spinlock
  • 29. PROFESSIONAL JS CONFERENCE Shared memory and multithreading in Node.js enter() { return new Promise(resolve => { const tryEnter = () => { let prev = Atomics.exchange(this.lock, 0, LOCKED); if (prev === UNLOCKED) { this.owner = true; resolve(); } else { setTimeout(tryEnter, 0); } }; tryEnter(); }); } Spinlock with setTimeout
  • 30. PROFESSIONAL JS CONFERENCE Shared memory and multithreading in Node.js constructor(messagePort, shared, offset = 0) { this.port = messagePort; this.lock = new Int32Array(shared, offset, 1); this.owner = false; this.trying = false; this.resolve = null; if (messagePort) { messagePort.on('message', kind => { if (kind === 'leave' && this.trying) this.tryEnter(); }); } Example: 8-async.js } Asynchronous Mutex
  • 31. PROFESSIONAL JS CONFERENCE Shared memory and multithreading in Node.js enter() { return new Promise(resolve => { this.resolve = resolve; this.trying = true; this.tryEnter(); }); } Asynchronous Mutex.enter
  • 32. PROFESSIONAL JS CONFERENCE Shared memory and multithreading in Node.js tryEnter() { if (!this.resolve) return; let prev = Atomics.exchange(this.lock, 0, LOCKED); if (prev === UNLOCKED) { this.owner = true; this.trying = false; this.resolve(); this.resolve = null; } } Asynchronous Mutex.tryEnter
  • 33. PROFESSIONAL JS CONFERENCE Shared memory and multithreading in Node.js - Low-level structures e.g. Register, Counter, Buffer, Array, Lists... - Abstract structures e.g. Queue, Graph, Polyline, etc. - Subject-domain classes e.g. Sensors, Payment, Biometric data, etc. Thread safe data structures
  • 34. PROFESSIONAL JS CONFERENCE Shared memory and multithreading in Node.js locks.request('resource', opt, async lock => { if (lock) { // critical section for `resource` // will be released after return } }); https://wicg.github.io/web-locks/ Web Locks API
  • 35. PROFESSIONAL JS CONFERENCE Shared memory and multithreading in Node.js - https://github.com/nodejs/node/issues/22702 Open - https://github.com/nodejs/node/pull/22719 Closed Web Locks for Node.js
  • 36. PROFESSIONAL JS CONFERENCE Shared memory and multithreading in Node.js - Web Locks requires memory + messaging - Multiple locks.request() calls requires queue - Mutex.queue: Array<Lock> // resource - Lock { name, mode, callback } // request - Need await locks.request() - Options: { mode, ifAvailable, steal, signal } Web Locks API Implementation
  • 37. PROFESSIONAL JS CONFERENCE Shared memory and multithreading in Node.js locks.request('resource', lock => new Promise( (resolve, reject) => { // you can store or pass resolve and // reject here as callbacks } )); https://wicg.github.io/web-locks/ Web Locks: Promise or thenable
  • 38. PROFESSIONAL JS CONFERENCE Shared memory and multithreading in Node.js const controller = new AbortController(); setTimeout(() => controller.abort(), 200); const { signal } = controller; locks.request('resource', { signal }, async lock => { // lock is held }).catch(err => { // err is AbortError }); Web Locks: Abort
  • 39. PROFESSIONAL JS CONFERENCE Shared memory and multithreading in Node.js - Passing handles between workers - Native add-ons (with certain conditions) - Debug - Experimental https://github.com/nodejs/node/issues/22940 To be solved
  • 40. PROFESSIONAL JS CONFERENCE Shared memory and multithreading in Node.js https://github.com/HowProgrammingWorks/Semaphore https://github.com/HowProgrammingWorks/Mutex https://github.com/metarhia/metasync https://wicg.github.io/web-locks https://nodejs.org/api/worker_threads.html https://developer.mozilla.org/en-US/docs/Web/ JavaScript/Reference/Global_Objects/Atomics Links
  • 41. PROFESSIONAL JS CONFERENCE Shared memory and multithreading in Node.js https://github.com/tshemsedinov https://www.youtube.com/TimurShemsedinov timur.shemsedinov@gmail.com Thanks