SlideShare a Scribd company logo
Threads and Node.js
Sakthipriyan Vairamani
Node.js Technical Steering Committee Member
Concurrency vs Parallelism
● Parallelism
○ Multiple execution units
○ Simultaneous execution
● Concurrency
○ Single execution unit
○ Time interleaved execution
Concurrency vs Parallelism
No concurrency, no parallelism
1 2 3 1 2 3 1 2 3
CPU Cycles
CPU 1
Concurrency, no parallelism
1 1 1 2 2 2 3 3 3
CPU Cycles
CPU 1
No concurrency, parallelism
1 2 3
1 2 3
1 2 3
CPU Cycles
CPU 1
CPU 2
CPU 3
Concurrency, parallelism
1 2 3
1 2 3
1 2 3
CPU Cycles
CPU 1
CPU 2
CPU 3
Execution Models
● Single tasking
○ One program, runs to completion
● Multi tasking
○ Co-operative
○ Pre-emptive
○ Multi Core
Process
● An instance of a program
○ Just like how objects are to classes
● Container for
○ Code
○ Memory (Stack, Heap, Data segment)
○ Resource Descriptors
○ State (Execution Context)
Process
Code Resource Descriptors Heap
Execution Context (Stack + Registers)
Main Thread
Thread
● Execution Context
○ Registers
○ Stack
● Associated with a process
● Share process’s resources and memory
● Can be multiple for a process
Thread
Code, Resources, and Heap
Context
Main Thread
Context Context
Thread 1 Thread 2
Node.js
● Single threaded
● Non-blocking IO
● Async APIs with callbacks
● Scalable
● Never block Node.js’s main thread
Node.js’s Asynchronicity and Threads
Event Loop
libuv
Thread PoolNode.js APIs
Userland JavaScript code
1
2
3
Node.js Worker Threads
● CPU Intensive Tasks
● Share main process’s resources, but not variables
● Can Share SharedArrayBuffer
● Message Passing
● Structured Cloning
Creating Worker Threads
// DO NOT RUN THIS
const { Worker } = require('worker_threads');
const w = new Worker(__filename);
Detect Main & Worker Threads
const { isMainThread, Worker } = require('worker_threads');
if (isMainThread) {
console.log('Inside Main Thread');
const w = new Worker(__filename);
} else {
console.log('Inside Worker Thread');
}
Pass initial context during Thread Creation
if (isMainThread) {
const w = new Worker(__filename, {
workerData: {
data: 'Node.js'
}
});
} else {
console.log(require('worker_threads').workerData);
}
Communication between Main and Worker Threads
const { isMainThread, parentPort, Worker } =
require('worker_threads');
if (isMainThread) {
const w = new Worker(__filename);
w.postMessage('Ping');
w.once('message', console.log);
w.on('exit', (exitCode) => console.log(exitCode));
} else {
parentPort.once('message', function (msg) {
if (msg === 'Ping') parentPort.postMessage('Pong');
});
}
Sharing Memory Between Threads
const i32Array = new Int32Array(new SharedArrayBuffer(12));
if (isMainThread) {
console.log(i32Array); // Int32Array [ 0, 0, 0 ]
const w = new Worker(__filename, {
workerData: i32Array
});
w.once('message', () => console.log(i32Array)); // Int32Array [ 1, 0, 0 ]
} else {
const data = require('worker_threads').workerData;
data[0] = 1;
parentPort.postMessage('Done');
}
● Atomic operations on SharedArrayBuffers
● Bunch of static functions
○ Atomics.store(sab, index, value)
○ Atomics.load(sab, index)
○ Atomics.add(sab, index, value)
○ ...
Atomics
Atomics and Mutable Shared Arrays
const i32Array = new Int32Array(new SharedArrayBuffer(12));
if (isMainThread) {
console.log(i32Array); // Int32Array [ 0, 0, 0 ]
const w = new Worker(__filename, {
workerData: i32Array
});
w.once('message', () => console.log(Atomics.load(i32Array, 0))); // 1
} else {
const data = require('worker_threads').workerData;
data[0] = 1;
parentPort.postMessage('Done');
}
Terminating Worker Threads
if (isMainThread) {
const w = new Worker(__filename);
console.log(w.threadId); // 1
w.postMessage(w.threadId);
w.once('message', (id) => {
console.log('Thread ID is', id);
w.terminate();
});
w.on('exit', console.log); // 0
} else {
parentPort.once('message', (msg) => {
let i = 0;
while (true) {
if (i++ === 10) {
parentPort.postMessage(require('worker_threads').threadId);
break; // Uncomment to change exit code
}
The Structured Clone Algorithm
● Clone/copy of the object
● Used during postMessage
● Error and Function cannot be cloned
● Property Descriptors, Setters, and Getters are ignored
● Prototype chain is ignored
Thank you!
Sakthipriyan Vairamani
Node.js Technical Steering Committee Member

More Related Content

What's hot

Disruptor 2015-12-22 @ java.il
Disruptor 2015-12-22 @ java.ilDisruptor 2015-12-22 @ java.il
Disruptor 2015-12-22 @ java.il
Amir Langer
 
File input output in Java
File input output in JavaFile input output in Java
File input output in Java
Fiverr
 
Mongodb meetup
Mongodb meetupMongodb meetup
Mongodb meetup
Eytan Daniyalzade
 
.NET Multithreading/Multitasking
.NET Multithreading/Multitasking.NET Multithreading/Multitasking
.NET Multithreading/Multitasking
Sasha Kravchuk
 
Aleksandr_Butenko_Mobile_Development
Aleksandr_Butenko_Mobile_DevelopmentAleksandr_Butenko_Mobile_Development
Aleksandr_Butenko_Mobile_Development
Ciklum
 
Apachecon Eu 2008 Mina
Apachecon Eu 2008 MinaApachecon Eu 2008 Mina
Apachecon Eu 2008 Mina
Niklas Gustavsson
 
Dicas e truques de otimização de websites python
Dicas e truques de otimização de websites pythonDicas e truques de otimização de websites python
Dicas e truques de otimização de websites python
Fabiano Weimar
 
PyConIT6 - MAKING SESSIONS AND CACHING ROOMMATES
PyConIT6 - MAKING SESSIONS AND CACHING ROOMMATESPyConIT6 - MAKING SESSIONS AND CACHING ROOMMATES
PyConIT6 - MAKING SESSIONS AND CACHING ROOMMATES
Alessandro Molina
 
zmq.rs - A brief history of concurrency in Rust
zmq.rs - A brief history of concurrency in Rustzmq.rs - A brief history of concurrency in Rust
zmq.rs - A brief history of concurrency in Rust
Fantix King 王川
 
Glusterd_thread_synchronization_using_urcu_lca2016
Glusterd_thread_synchronization_using_urcu_lca2016Glusterd_thread_synchronization_using_urcu_lca2016
Glusterd_thread_synchronization_using_urcu_lca2016
Atin Mukherjee
 
Grand Central Dispatch - iOS Conf SG 2015
Grand Central Dispatch - iOS Conf SG 2015Grand Central Dispatch - iOS Conf SG 2015
Grand Central Dispatch - iOS Conf SG 2015
Ben Asher
 
Concurrency: Rubies, Plural
Concurrency: Rubies, PluralConcurrency: Rubies, Plural
Concurrency: Rubies, Plural
Eleanor McHugh
 
Concurrency: Rubies, plural
Concurrency: Rubies, pluralConcurrency: Rubies, plural
Concurrency: Rubies, plural
ehuard
 
GCD and OperationQueue.
GCD and OperationQueue.GCD and OperationQueue.
GCD and OperationQueue.
HSIEH CHING-FAN
 
Tech Talk #4 : Multi - threading and GCD ( grand central dispatch ) in iOS - ...
Tech Talk #4 : Multi - threading and GCD ( grand central dispatch ) in iOS - ...Tech Talk #4 : Multi - threading and GCD ( grand central dispatch ) in iOS - ...
Tech Talk #4 : Multi - threading and GCD ( grand central dispatch ) in iOS - ...
Nexus FrontierTech
 
Jafka guide
Jafka guideJafka guide
Jafka guide
Ady Liu
 
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
Stoyan Nikolov
 
PyConIT6 - Messing up with pymongo for fun and profit
PyConIT6 - Messing up with pymongo for fun and profitPyConIT6 - Messing up with pymongo for fun and profit
PyConIT6 - Messing up with pymongo for fun and profit
Alessandro Molina
 
#2 (UDP)
#2 (UDP)#2 (UDP)
#2 (UDP)
Ghadeer AlHasan
 

What's hot (19)

Disruptor 2015-12-22 @ java.il
Disruptor 2015-12-22 @ java.ilDisruptor 2015-12-22 @ java.il
Disruptor 2015-12-22 @ java.il
 
File input output in Java
File input output in JavaFile input output in Java
File input output in Java
 
Mongodb meetup
Mongodb meetupMongodb meetup
Mongodb meetup
 
.NET Multithreading/Multitasking
.NET Multithreading/Multitasking.NET Multithreading/Multitasking
.NET Multithreading/Multitasking
 
Aleksandr_Butenko_Mobile_Development
Aleksandr_Butenko_Mobile_DevelopmentAleksandr_Butenko_Mobile_Development
Aleksandr_Butenko_Mobile_Development
 
Apachecon Eu 2008 Mina
Apachecon Eu 2008 MinaApachecon Eu 2008 Mina
Apachecon Eu 2008 Mina
 
Dicas e truques de otimização de websites python
Dicas e truques de otimização de websites pythonDicas e truques de otimização de websites python
Dicas e truques de otimização de websites python
 
PyConIT6 - MAKING SESSIONS AND CACHING ROOMMATES
PyConIT6 - MAKING SESSIONS AND CACHING ROOMMATESPyConIT6 - MAKING SESSIONS AND CACHING ROOMMATES
PyConIT6 - MAKING SESSIONS AND CACHING ROOMMATES
 
zmq.rs - A brief history of concurrency in Rust
zmq.rs - A brief history of concurrency in Rustzmq.rs - A brief history of concurrency in Rust
zmq.rs - A brief history of concurrency in Rust
 
Glusterd_thread_synchronization_using_urcu_lca2016
Glusterd_thread_synchronization_using_urcu_lca2016Glusterd_thread_synchronization_using_urcu_lca2016
Glusterd_thread_synchronization_using_urcu_lca2016
 
Grand Central Dispatch - iOS Conf SG 2015
Grand Central Dispatch - iOS Conf SG 2015Grand Central Dispatch - iOS Conf SG 2015
Grand Central Dispatch - iOS Conf SG 2015
 
Concurrency: Rubies, Plural
Concurrency: Rubies, PluralConcurrency: Rubies, Plural
Concurrency: Rubies, Plural
 
Concurrency: Rubies, plural
Concurrency: Rubies, pluralConcurrency: Rubies, plural
Concurrency: Rubies, plural
 
GCD and OperationQueue.
GCD and OperationQueue.GCD and OperationQueue.
GCD and OperationQueue.
 
Tech Talk #4 : Multi - threading and GCD ( grand central dispatch ) in iOS - ...
Tech Talk #4 : Multi - threading and GCD ( grand central dispatch ) in iOS - ...Tech Talk #4 : Multi - threading and GCD ( grand central dispatch ) in iOS - ...
Tech Talk #4 : Multi - threading and GCD ( grand central dispatch ) in iOS - ...
 
Jafka guide
Jafka guideJafka guide
Jafka guide
 
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
 
PyConIT6 - Messing up with pymongo for fun and profit
PyConIT6 - Messing up with pymongo for fun and profitPyConIT6 - Messing up with pymongo for fun and profit
PyConIT6 - Messing up with pymongo for fun and profit
 
#2 (UDP)
#2 (UDP)#2 (UDP)
#2 (UDP)
 

Similar to Threads and Node.js

OpenHPI - Parallel Programming Concepts - Week 3
OpenHPI - Parallel Programming Concepts - Week 3OpenHPI - Parallel Programming Concepts - Week 3
OpenHPI - Parallel Programming Concepts - Week 3
Peter Tröger
 
Java Concurrency in Practice
Java Concurrency in PracticeJava Concurrency in Practice
Java Concurrency in Practice
Alina Dolgikh
 
Node js
Node jsNode js
Node js
hazzaz
 
Node js lecture
Node js lectureNode js lecture
Node js lecture
Darryl Sherman
 
NodeJSnodesforfreeinmyworldgipsnndnnd.pdf
NodeJSnodesforfreeinmyworldgipsnndnnd.pdfNodeJSnodesforfreeinmyworldgipsnndnnd.pdf
NodeJSnodesforfreeinmyworldgipsnndnnd.pdf
VivekSonawane45
 
Binary Studio Academy: Concurrency in C# 5.0
Binary Studio Academy: Concurrency in C# 5.0Binary Studio Academy: Concurrency in C# 5.0
Binary Studio Academy: Concurrency in C# 5.0
Binary Studio
 
Dragoncraft Architectural Overview
Dragoncraft Architectural OverviewDragoncraft Architectural Overview
Dragoncraft Architectural Overview
jessesanford
 
Multi-core Node.pdf
Multi-core Node.pdfMulti-core Node.pdf
Multi-core Node.pdf
Ahmed Hassan
 
WEEK07operatingsystemdepartmentofsoftwareengineering.pptx
WEEK07operatingsystemdepartmentofsoftwareengineering.pptxWEEK07operatingsystemdepartmentofsoftwareengineering.pptx
WEEK07operatingsystemdepartmentofsoftwareengineering.pptx
babayaga920391
 
Java concurrency
Java concurrencyJava concurrency
Java concurrency
Hithem Ahmed
 
Parallel programming patterns - Олександр Павлишак
Parallel programming patterns - Олександр ПавлишакParallel programming patterns - Олександр Павлишак
Parallel programming patterns - Олександр Павлишак
Igor Bronovskyy
 
Parallel programming patterns (UA)
Parallel programming patterns (UA)Parallel programming patterns (UA)
Parallel programming patterns (UA)
Oleksandr Pavlyshak
 
Parallel Programming With Dot Net
Parallel Programming With Dot NetParallel Programming With Dot Net
Parallel Programming With Dot Net
Neeraj Kaushik
 
Journey through high performance django application
Journey through high performance django applicationJourney through high performance django application
Journey through high performance django application
bangaloredjangousergroup
 
Java Memory Model
Java Memory ModelJava Memory Model
Java Memory Model
Łukasz Koniecki
 
Node.js concurrency
Node.js concurrencyNode.js concurrency
Node.js concurrency
Giacomo Fornari
 
Caching in (DevoxxUK 2013)
Caching in (DevoxxUK 2013)Caching in (DevoxxUK 2013)
Caching in (DevoxxUK 2013)
RichardWarburton
 
Parallel program design
Parallel program designParallel program design
Parallel program design
ZongYing Lyu
 
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
 
Lockless Programming GDC 09
Lockless Programming GDC 09Lockless Programming GDC 09
Lockless Programming GDC 09
Lee Hanxue
 

Similar to Threads and Node.js (20)

OpenHPI - Parallel Programming Concepts - Week 3
OpenHPI - Parallel Programming Concepts - Week 3OpenHPI - Parallel Programming Concepts - Week 3
OpenHPI - Parallel Programming Concepts - Week 3
 
Java Concurrency in Practice
Java Concurrency in PracticeJava Concurrency in Practice
Java Concurrency in Practice
 
Node js
Node jsNode js
Node js
 
Node js lecture
Node js lectureNode js lecture
Node js lecture
 
NodeJSnodesforfreeinmyworldgipsnndnnd.pdf
NodeJSnodesforfreeinmyworldgipsnndnnd.pdfNodeJSnodesforfreeinmyworldgipsnndnnd.pdf
NodeJSnodesforfreeinmyworldgipsnndnnd.pdf
 
Binary Studio Academy: Concurrency in C# 5.0
Binary Studio Academy: Concurrency in C# 5.0Binary Studio Academy: Concurrency in C# 5.0
Binary Studio Academy: Concurrency in C# 5.0
 
Dragoncraft Architectural Overview
Dragoncraft Architectural OverviewDragoncraft Architectural Overview
Dragoncraft Architectural Overview
 
Multi-core Node.pdf
Multi-core Node.pdfMulti-core Node.pdf
Multi-core Node.pdf
 
WEEK07operatingsystemdepartmentofsoftwareengineering.pptx
WEEK07operatingsystemdepartmentofsoftwareengineering.pptxWEEK07operatingsystemdepartmentofsoftwareengineering.pptx
WEEK07operatingsystemdepartmentofsoftwareengineering.pptx
 
Java concurrency
Java concurrencyJava concurrency
Java concurrency
 
Parallel programming patterns - Олександр Павлишак
Parallel programming patterns - Олександр ПавлишакParallel programming patterns - Олександр Павлишак
Parallel programming patterns - Олександр Павлишак
 
Parallel programming patterns (UA)
Parallel programming patterns (UA)Parallel programming patterns (UA)
Parallel programming patterns (UA)
 
Parallel Programming With Dot Net
Parallel Programming With Dot NetParallel Programming With Dot Net
Parallel Programming With Dot Net
 
Journey through high performance django application
Journey through high performance django applicationJourney through high performance django application
Journey through high performance django application
 
Java Memory Model
Java Memory ModelJava Memory Model
Java Memory Model
 
Node.js concurrency
Node.js concurrencyNode.js concurrency
Node.js concurrency
 
Caching in (DevoxxUK 2013)
Caching in (DevoxxUK 2013)Caching in (DevoxxUK 2013)
Caching in (DevoxxUK 2013)
 
Parallel program design
Parallel program designParallel program design
Parallel program design
 
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
 
Lockless Programming GDC 09
Lockless Programming GDC 09Lockless Programming GDC 09
Lockless Programming GDC 09
 

Recently uploaded

Presentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of GermanyPresentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of Germany
innovationoecd
 
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdfUnlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Malak Abu Hammad
 
UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6
DianaGray10
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
Aftab Hussain
 
Full-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalizationFull-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalization
Zilliz
 
How to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For FlutterHow to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For Flutter
Daiki Mogmet Ito
 
Artificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopmentArtificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopment
Octavian Nadolu
 
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
SOFTTECHHUB
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
Safe Software
 
Climate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing DaysClimate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing Days
Kari Kakkonen
 
Mind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AIMind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AI
Kumud Singh
 
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
名前 です男
 
Microsoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdfMicrosoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdf
Uni Systems S.M.S.A.
 
TrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy SurveyTrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy Survey
TrustArc
 
Driving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success StoryDriving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success Story
Safe Software
 
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfObservability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Paige Cruz
 
“I’m still / I’m still / Chaining from the Block”
“I’m still / I’m still / Chaining from the Block”“I’m still / I’m still / Chaining from the Block”
“I’m still / I’m still / Chaining from the Block”
Claudio Di Ciccio
 
20240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 202420240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 2024
Matthew Sinclair
 
RESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for studentsRESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for students
KAMESHS29
 
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with SlackLet's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
shyamraj55
 

Recently uploaded (20)

Presentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of GermanyPresentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of Germany
 
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdfUnlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
 
UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
 
Full-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalizationFull-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalization
 
How to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For FlutterHow to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For Flutter
 
Artificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopmentArtificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopment
 
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
 
Climate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing DaysClimate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing Days
 
Mind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AIMind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AI
 
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
 
Microsoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdfMicrosoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdf
 
TrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy SurveyTrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy Survey
 
Driving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success StoryDriving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success Story
 
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfObservability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
 
“I’m still / I’m still / Chaining from the Block”
“I’m still / I’m still / Chaining from the Block”“I’m still / I’m still / Chaining from the Block”
“I’m still / I’m still / Chaining from the Block”
 
20240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 202420240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 2024
 
RESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for studentsRESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for students
 
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with SlackLet's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
 

Threads and Node.js

  • 1. Threads and Node.js Sakthipriyan Vairamani Node.js Technical Steering Committee Member
  • 2. Concurrency vs Parallelism ● Parallelism ○ Multiple execution units ○ Simultaneous execution ● Concurrency ○ Single execution unit ○ Time interleaved execution
  • 3. Concurrency vs Parallelism No concurrency, no parallelism 1 2 3 1 2 3 1 2 3 CPU Cycles CPU 1 Concurrency, no parallelism 1 1 1 2 2 2 3 3 3 CPU Cycles CPU 1 No concurrency, parallelism 1 2 3 1 2 3 1 2 3 CPU Cycles CPU 1 CPU 2 CPU 3 Concurrency, parallelism 1 2 3 1 2 3 1 2 3 CPU Cycles CPU 1 CPU 2 CPU 3
  • 4. Execution Models ● Single tasking ○ One program, runs to completion ● Multi tasking ○ Co-operative ○ Pre-emptive ○ Multi Core
  • 5. Process ● An instance of a program ○ Just like how objects are to classes ● Container for ○ Code ○ Memory (Stack, Heap, Data segment) ○ Resource Descriptors ○ State (Execution Context)
  • 6. Process Code Resource Descriptors Heap Execution Context (Stack + Registers) Main Thread
  • 7. Thread ● Execution Context ○ Registers ○ Stack ● Associated with a process ● Share process’s resources and memory ● Can be multiple for a process
  • 8. Thread Code, Resources, and Heap Context Main Thread Context Context Thread 1 Thread 2
  • 9. Node.js ● Single threaded ● Non-blocking IO ● Async APIs with callbacks ● Scalable ● Never block Node.js’s main thread
  • 10. Node.js’s Asynchronicity and Threads Event Loop libuv Thread PoolNode.js APIs Userland JavaScript code 1 2 3
  • 11. Node.js Worker Threads ● CPU Intensive Tasks ● Share main process’s resources, but not variables ● Can Share SharedArrayBuffer ● Message Passing ● Structured Cloning
  • 12. Creating Worker Threads // DO NOT RUN THIS const { Worker } = require('worker_threads'); const w = new Worker(__filename);
  • 13. Detect Main & Worker Threads const { isMainThread, Worker } = require('worker_threads'); if (isMainThread) { console.log('Inside Main Thread'); const w = new Worker(__filename); } else { console.log('Inside Worker Thread'); }
  • 14. Pass initial context during Thread Creation if (isMainThread) { const w = new Worker(__filename, { workerData: { data: 'Node.js' } }); } else { console.log(require('worker_threads').workerData); }
  • 15. Communication between Main and Worker Threads const { isMainThread, parentPort, Worker } = require('worker_threads'); if (isMainThread) { const w = new Worker(__filename); w.postMessage('Ping'); w.once('message', console.log); w.on('exit', (exitCode) => console.log(exitCode)); } else { parentPort.once('message', function (msg) { if (msg === 'Ping') parentPort.postMessage('Pong'); }); }
  • 16. Sharing Memory Between Threads const i32Array = new Int32Array(new SharedArrayBuffer(12)); if (isMainThread) { console.log(i32Array); // Int32Array [ 0, 0, 0 ] const w = new Worker(__filename, { workerData: i32Array }); w.once('message', () => console.log(i32Array)); // Int32Array [ 1, 0, 0 ] } else { const data = require('worker_threads').workerData; data[0] = 1; parentPort.postMessage('Done'); }
  • 17. ● Atomic operations on SharedArrayBuffers ● Bunch of static functions ○ Atomics.store(sab, index, value) ○ Atomics.load(sab, index) ○ Atomics.add(sab, index, value) ○ ... Atomics
  • 18. Atomics and Mutable Shared Arrays const i32Array = new Int32Array(new SharedArrayBuffer(12)); if (isMainThread) { console.log(i32Array); // Int32Array [ 0, 0, 0 ] const w = new Worker(__filename, { workerData: i32Array }); w.once('message', () => console.log(Atomics.load(i32Array, 0))); // 1 } else { const data = require('worker_threads').workerData; data[0] = 1; parentPort.postMessage('Done'); }
  • 19. Terminating Worker Threads if (isMainThread) { const w = new Worker(__filename); console.log(w.threadId); // 1 w.postMessage(w.threadId); w.once('message', (id) => { console.log('Thread ID is', id); w.terminate(); }); w.on('exit', console.log); // 0 } else { parentPort.once('message', (msg) => { let i = 0; while (true) { if (i++ === 10) { parentPort.postMessage(require('worker_threads').threadId); break; // Uncomment to change exit code }
  • 20. The Structured Clone Algorithm ● Clone/copy of the object ● Used during postMessage ● Error and Function cannot be cloned ● Property Descriptors, Setters, and Getters are ignored ● Prototype chain is ignored
  • 21. Thank you! Sakthipriyan Vairamani Node.js Technical Steering Committee Member