SlideShare a Scribd company logo
1 of 41
Download to read offline
Timur Shemsedinov
5-6 APRIL
Introduction to multithreading concurrent programming in
Node.js with worker_threads, SharedArrayBuffer and Atomics
Shared memory and
multithreading in Node.js
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
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
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
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)
Shared memory and multithreading in Node.js
Node.js: worker_threads
Read-only in Worker threads:
- process.env
- process.title
- process.umask([mask])
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
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;
}
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) => {});
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
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
Shared memory and multithreading in Node.js
- Parallel Programming
- Asynchronous Programming
- Actor Model
- Transactional Memory
- Coroutines
Concurrent Computing
Shared memory and multithreading in Node.js
Parallel Programming
- Race condition
- Critical section
- Deadlock
- Livelock
- Starvation
Shared memory and multithreading in Node.js
Int8Array, Uint8Array,
Int16Array, Uint16Array,
Int32Array, Uint32Array
Atomics and SharedArrayBuffer
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
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)
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)
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)
Shared memory and multithreading in Node.js
Synchronization primitives
- Semaphore
- BinarySemaphore
- CountingSemaphore
- Condition variable
- SpinLock
- Mutex
- TimedMutex
- SharedMutex
- RecursiveMutex
- Monitor
- Barrier
Shared memory and multithreading in Node.js
- thread safe data structures
- lock-free data structures
- wait-free algorithms
- conflict-free data structures
Parallel Solutions
Shared memory and multithreading in Node.js
class Mutex {
constructor(shared, offset = 0)
enter()
leave()
}
https://github.com/HowProgrammingWorks/Mutex
Mutex
Shared memory and multithreading in Node.js
mutex.enter();
// do something
// with shared resources
// or data structures
mutex.leave();
Mutex usage
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
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
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
Shared memory and multithreading in Node.js
mutex.enter(() => {
// do something
// with shared resources
// or data structures
mutex.leave();
});
Async Mutex usage
Shared memory and multithreading in Node.js
await mutex.enter();
// do something
// with shared resources
// or data structures
mutex.leave();
Async Mutex usage
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
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
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
Shared memory and multithreading in Node.js
enter() {
return new Promise(resolve => {
this.resolve = resolve;
this.trying = true;
this.tryEnter();
});
}
Asynchronous Mutex.enter
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
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
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
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
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
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
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
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
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
Shared memory and multithreading in Node.js
https://github.com/tshemsedinov
https://www.youtube.com/TimurShemsedinov
timur.shemsedinov@gmail.com
Thanks

More Related Content

What's hot

What's hot (20)

AWS Transit Gateway를 통한 Multi-VPC 아키텍처 패턴 - 강동환 솔루션즈 아키텍트, AWS :: AWS Summit ...
AWS Transit Gateway를 통한 Multi-VPC 아키텍처 패턴 - 강동환 솔루션즈 아키텍트, AWS :: AWS Summit ...AWS Transit Gateway를 통한 Multi-VPC 아키텍처 패턴 - 강동환 솔루션즈 아키텍트, AWS :: AWS Summit ...
AWS Transit Gateway를 통한 Multi-VPC 아키텍처 패턴 - 강동환 솔루션즈 아키텍트, AWS :: AWS Summit ...
 
Session 4 - Bringing the pieces together - Detailed review of a reference ex...
Session 4 -  Bringing the pieces together - Detailed review of a reference ex...Session 4 -  Bringing the pieces together - Detailed review of a reference ex...
Session 4 - Bringing the pieces together - Detailed review of a reference ex...
 
Node.js Express Framework
Node.js Express FrameworkNode.js Express Framework
Node.js Express Framework
 
Centralized SOC Architectures on AWS
Centralized SOC Architectures on AWSCentralized SOC Architectures on AWS
Centralized SOC Architectures on AWS
 
i4Trust IAM Components
i4Trust IAM Componentsi4Trust IAM Components
i4Trust IAM Components
 
Session 3 - i4Trust components for Identity Management and Access Control i4T...
Session 3 - i4Trust components for Identity Management and Access Control i4T...Session 3 - i4Trust components for Identity Management and Access Control i4T...
Session 3 - i4Trust components for Identity Management and Access Control i4T...
 
Improving the performance of Odoo deployments
Improving the performance of Odoo deploymentsImproving the performance of Odoo deployments
Improving the performance of Odoo deployments
 
스마트 팩토리: AWS 사물인터넷과 인공지능을 활용한 스마트 팩토리 구축 – 최영준 AWS 솔루션즈 아키텍트, 정현아 AWS 솔루션즈 아키...
스마트 팩토리: AWS 사물인터넷과 인공지능을 활용한 스마트 팩토리 구축 – 최영준 AWS 솔루션즈 아키텍트, 정현아 AWS 솔루션즈 아키...스마트 팩토리: AWS 사물인터넷과 인공지능을 활용한 스마트 팩토리 구축 – 최영준 AWS 솔루션즈 아키텍트, 정현아 AWS 솔루션즈 아키...
스마트 팩토리: AWS 사물인터넷과 인공지능을 활용한 스마트 팩토리 구축 – 최영준 AWS 솔루션즈 아키텍트, 정현아 AWS 솔루션즈 아키...
 
Session 5 - NGSI-LD Advanced Operations | Train the Trainers Program
Session 5 -  NGSI-LD Advanced Operations | Train the Trainers ProgramSession 5 -  NGSI-LD Advanced Operations | Train the Trainers Program
Session 5 - NGSI-LD Advanced Operations | Train the Trainers Program
 
KB금융지주의 클라우드 혁신 사례 – 협업플랫폼 Clayon - 고종원 매니저, AWS / 박형주 부장, KB금융지주 :: AWS Summ...
KB금융지주의 클라우드 혁신 사례 – 협업플랫폼 Clayon - 고종원 매니저, AWS / 박형주 부장, KB금융지주 :: AWS Summ...KB금융지주의 클라우드 혁신 사례 – 협업플랫폼 Clayon - 고종원 매니저, AWS / 박형주 부장, KB금융지주 :: AWS Summ...
KB금융지주의 클라우드 혁신 사례 – 협업플랫폼 Clayon - 고종원 매니저, AWS / 박형주 부장, KB금융지주 :: AWS Summ...
 
Node js Modules and Event Emitters
Node js Modules and Event EmittersNode js Modules and Event Emitters
Node js Modules and Event Emitters
 
Going realtime with Socket.IO
Going realtime with Socket.IOGoing realtime with Socket.IO
Going realtime with Socket.IO
 
REST-API design patterns
REST-API design patternsREST-API design patterns
REST-API design patterns
 
Content Management with MongoDB by Mark Helmstetter
 Content Management with MongoDB by Mark Helmstetter Content Management with MongoDB by Mark Helmstetter
Content Management with MongoDB by Mark Helmstetter
 
[2019] HTTP API 설계 후회 고민
[2019] HTTP API 설계 후회 고민[2019] HTTP API 설계 후회 고민
[2019] HTTP API 설계 후회 고민
 
Query Pre Payment details Oracle Fusion Cloud
Query Pre Payment details Oracle Fusion CloudQuery Pre Payment details Oracle Fusion Cloud
Query Pre Payment details Oracle Fusion Cloud
 
Demystifying AuthN/AuthZ Using OIDC & OAuth2
Demystifying AuthN/AuthZ Using OIDC & OAuth2Demystifying AuthN/AuthZ Using OIDC & OAuth2
Demystifying AuthN/AuthZ Using OIDC & OAuth2
 
AWS 마켓플레이스 성공 런칭을 위한 핵심 기술 (이경수, AWS 솔루션즈아키텍트) :: AWS TechShift 2018
AWS 마켓플레이스 성공 런칭을 위한 핵심 기술 (이경수, AWS 솔루션즈아키텍트) :: AWS TechShift 2018AWS 마켓플레이스 성공 런칭을 위한 핵심 기술 (이경수, AWS 솔루션즈아키텍트) :: AWS TechShift 2018
AWS 마켓플레이스 성공 런칭을 위한 핵심 기술 (이경수, AWS 솔루션즈아키텍트) :: AWS TechShift 2018
 
Payroll costing details Oracle Fusion Cloud HCM
Payroll costing details Oracle Fusion Cloud HCMPayroll costing details Oracle Fusion Cloud HCM
Payroll costing details Oracle Fusion Cloud HCM
 
AWS IAM과 친해지기 – 조이정, AWS 솔루션즈 아키텍트:: AWS Builders Online Series
AWS IAM과 친해지기 – 조이정, AWS 솔루션즈 아키텍트:: AWS Builders Online Series AWS IAM과 친해지기 – 조이정, AWS 솔루션즈 아키텍트:: AWS Builders Online Series
AWS IAM과 친해지기 – 조이정, AWS 솔루션즈 아키텍트:: AWS Builders Online Series
 

Similar to Shared memory and multithreading in Node.js - Timur Shemsedinov - JSFest'19

Medical Image Processing Strategies for multi-core CPUs
Medical Image Processing Strategies for multi-core CPUsMedical Image Processing Strategies for multi-core CPUs
Medical Image Processing Strategies for multi-core CPUs
Daniel Blezek
 

Similar to Shared memory and multithreading in Node.js - Timur Shemsedinov - JSFest'19 (20)

JS Fest 2019. Тимур Шемсединов. Разделяемая память в многопоточном Node.js
JS Fest 2019. Тимур Шемсединов. Разделяемая память в многопоточном Node.jsJS Fest 2019. Тимур Шемсединов. Разделяемая память в многопоточном Node.js
JS Fest 2019. Тимур Шемсединов. Разделяемая память в многопоточном Node.js
 
Java и Linux — особенности эксплуатации / Алексей Рагозин (Дойче Банк)
Java и Linux — особенности эксплуатации / Алексей Рагозин (Дойче Банк)Java и Linux — особенности эксплуатации / Алексей Рагозин (Дойче Банк)
Java и Linux — особенности эксплуатации / Алексей Рагозин (Дойче Банк)
 
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
 
Top 30 Node.js interview questions
Top 30 Node.js interview questionsTop 30 Node.js interview questions
Top 30 Node.js interview questions
 
Node.js Introduction
Node.js IntroductionNode.js Introduction
Node.js Introduction
 
Threads and Node.js
Threads and Node.jsThreads and Node.js
Threads and Node.js
 
Java concurrency introduction
Java concurrency introductionJava concurrency introduction
Java concurrency introduction
 
Nodejs Intro Part One
Nodejs Intro Part OneNodejs Intro Part One
Nodejs Intro Part One
 
Layered Caching in OpenResty
Layered Caching in OpenRestyLayered Caching in OpenResty
Layered Caching in OpenResty
 
NodeJS for Beginner
NodeJS for BeginnerNodeJS for Beginner
NodeJS for Beginner
 
Gpu computing workshop
Gpu computing workshopGpu computing workshop
Gpu computing workshop
 
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
 
What is nodejs
What is nodejsWhat is nodejs
What is nodejs
 
Medical Image Processing Strategies for multi-core CPUs
Medical Image Processing Strategies for multi-core CPUsMedical Image Processing Strategies for multi-core CPUs
Medical Image Processing Strategies for multi-core CPUs
 
Jaap : node, npm & grunt
Jaap : node, npm & gruntJaap : node, npm & grunt
Jaap : node, npm & grunt
 
Elastic101tutorial Percona Live Europe 2018
Elastic101tutorial Percona Live Europe 2018Elastic101tutorial Percona Live Europe 2018
Elastic101tutorial Percona Live Europe 2018
 
Elastic 101 tutorial - Percona Europe 2018
Elastic 101 tutorial - Percona Europe 2018 Elastic 101 tutorial - Percona Europe 2018
Elastic 101 tutorial - Percona Europe 2018
 
soft-shake.ch - Hands on Node.js
soft-shake.ch - Hands on Node.jssoft-shake.ch - Hands on Node.js
soft-shake.ch - Hands on Node.js
 
NodeJS
NodeJSNodeJS
NodeJS
 
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
 

More from Timur Shemsedinov

Information system structure and architecture
Information system structure and architectureInformation system structure and architecture
Information system structure and architecture
Timur Shemsedinov
 
Node.js in 2020 - part 1
Node.js in 2020 - part 1Node.js in 2020 - part 1
Node.js in 2020 - part 1
Timur Shemsedinov
 

More from Timur Shemsedinov (20)

How to use Chat GPT in JavaScript optimizations for Node.js
How to use Chat GPT in JavaScript optimizations for Node.jsHow to use Chat GPT in JavaScript optimizations for Node.js
How to use Chat GPT in JavaScript optimizations for Node.js
 
IT Revolution in 2023-2024: AI, GPT, business transformation, future professi...
IT Revolution in 2023-2024: AI, GPT, business transformation, future professi...IT Revolution in 2023-2024: AI, GPT, business transformation, future professi...
IT Revolution in 2023-2024: AI, GPT, business transformation, future professi...
 
Multithreading in Node.js and JavaScript
Multithreading in Node.js and JavaScriptMultithreading in Node.js and JavaScript
Multithreading in Node.js and JavaScript
 
Node.js threads for I/O-bound tasks
Node.js threads for I/O-bound tasksNode.js threads for I/O-bound tasks
Node.js threads for I/O-bound tasks
 
Node.js Меньше сложности, больше надежности Holy.js 2021
Node.js Меньше сложности, больше надежности Holy.js 2021Node.js Меньше сложности, больше надежности Holy.js 2021
Node.js Меньше сложности, больше надежности Holy.js 2021
 
Rethinking low-code
Rethinking low-codeRethinking low-code
Rethinking low-code
 
Hat full of developers
Hat full of developersHat full of developers
Hat full of developers
 
FwDays 2021: Metarhia Technology Stack for Node.js
FwDays 2021: Metarhia Technology Stack for Node.jsFwDays 2021: Metarhia Technology Stack for Node.js
FwDays 2021: Metarhia Technology Stack for Node.js
 
Node.js for enterprise - JS Conference
Node.js for enterprise - JS ConferenceNode.js for enterprise - JS Conference
Node.js for enterprise - JS Conference
 
Node.js for enterprise 2021 - JavaScript Fwdays 3
Node.js for enterprise 2021 - JavaScript Fwdays 3Node.js for enterprise 2021 - JavaScript Fwdays 3
Node.js for enterprise 2021 - JavaScript Fwdays 3
 
Node.js in 2021
Node.js in 2021Node.js in 2021
Node.js in 2021
 
Node.js middleware: Never again!
Node.js middleware: Never again!Node.js middleware: Never again!
Node.js middleware: Never again!
 
Patterns and antipatterns
Patterns and antipatternsPatterns and antipatterns
Patterns and antipatterns
 
Race-conditions-web-locks-and-shared-memory
Race-conditions-web-locks-and-shared-memoryRace-conditions-web-locks-and-shared-memory
Race-conditions-web-locks-and-shared-memory
 
Asynchronous programming and mutlithreading
Asynchronous programming and mutlithreadingAsynchronous programming and mutlithreading
Asynchronous programming and mutlithreading
 
Node.js in 2020 - part 3
Node.js in 2020 - part 3Node.js in 2020 - part 3
Node.js in 2020 - part 3
 
Node.js in 2020 - part 2
Node.js in 2020 - part 2Node.js in 2020 - part 2
Node.js in 2020 - part 2
 
Information system structure and architecture
Information system structure and architectureInformation system structure and architecture
Information system structure and architecture
 
Node.js in 2020 - part 1
Node.js in 2020 - part 1Node.js in 2020 - part 1
Node.js in 2020 - part 1
 
Web Locks API
Web Locks APIWeb Locks API
Web Locks API
 

Recently uploaded

%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
masabamasaba
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
masabamasaba
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
masabamasaba
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
Health
 
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
chiefasafspells
 

Recently uploaded (20)

WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
 
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
 
What Goes Wrong with Language Definitions and How to Improve the Situation
What Goes Wrong with Language Definitions and How to Improve the SituationWhat Goes Wrong with Language Definitions and How to Improve the Situation
What Goes Wrong with Language Definitions and How to Improve the Situation
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
 
%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benoni%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benoni
 
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With SimplicityWSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
 
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
 
Artyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptxArtyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptx
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
 
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 
WSO2Con204 - Hard Rock Presentation - Keynote
WSO2Con204 - Hard Rock Presentation - KeynoteWSO2Con204 - Hard Rock Presentation - Keynote
WSO2Con204 - Hard Rock Presentation - Keynote
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the past
 
WSO2CON 2024 - How to Run a Security Program
WSO2CON 2024 - How to Run a Security ProgramWSO2CON 2024 - How to Run a Security Program
WSO2CON 2024 - How to Run a Security Program
 
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
 

Shared memory and multithreading in Node.js - Timur Shemsedinov - JSFest'19

  • 1. Timur Shemsedinov 5-6 APRIL Introduction to multithreading concurrent programming in Node.js with worker_threads, SharedArrayBuffer and Atomics Shared memory and multithreading in Node.js
  • 2. 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. 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 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. 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. Shared memory and multithreading in Node.js Node.js: worker_threads Read-only in Worker threads: - process.env - process.title - process.umask([mask])
  • 7. 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. 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. 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. 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. 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. Shared memory and multithreading in Node.js - Parallel Programming - Asynchronous Programming - Actor Model - Transactional Memory - Coroutines Concurrent Computing
  • 13. Shared memory and multithreading in Node.js Parallel Programming - Race condition - Critical section - Deadlock - Livelock - Starvation
  • 14. Shared memory and multithreading in Node.js Int8Array, Uint8Array, Int16Array, Uint16Array, Int32Array, Uint32Array Atomics and SharedArrayBuffer
  • 15. 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. 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. 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. 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. Shared memory and multithreading in Node.js Synchronization primitives - Semaphore - BinarySemaphore - CountingSemaphore - Condition variable - SpinLock - Mutex - TimedMutex - SharedMutex - RecursiveMutex - Monitor - Barrier
  • 20. 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. Shared memory and multithreading in Node.js class Mutex { constructor(shared, offset = 0) enter() leave() } https://github.com/HowProgrammingWorks/Mutex Mutex
  • 22. Shared memory and multithreading in Node.js mutex.enter(); // do something // with shared resources // or data structures mutex.leave(); Mutex usage
  • 23. 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. 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. 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. Shared memory and multithreading in Node.js mutex.enter(() => { // do something // with shared resources // or data structures mutex.leave(); }); Async Mutex usage
  • 27. Shared memory and multithreading in Node.js await mutex.enter(); // do something // with shared resources // or data structures mutex.leave(); Async Mutex usage
  • 28. 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. 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. 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. Shared memory and multithreading in Node.js enter() { return new Promise(resolve => { this.resolve = resolve; this.trying = true; this.tryEnter(); }); } Asynchronous Mutex.enter
  • 32. 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. 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. 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. 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. 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. 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. 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. 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. 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. Shared memory and multithreading in Node.js https://github.com/tshemsedinov https://www.youtube.com/TimurShemsedinov timur.shemsedinov@gmail.com Thanks