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
Ad

More Related Content

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
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
 
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
 
.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
 
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
 
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
 

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
Peter Tröger
 
Java Concurrency in Practice
Java Concurrency in PracticeJava Concurrency in Practice
Java Concurrency in Practice
Alina Dolgikh
 
MultiThreading-in-system-and-android-logcat-42-.pdf
MultiThreading-in-system-and-android-logcat-42-.pdfMultiThreading-in-system-and-android-logcat-42-.pdf
MultiThreading-in-system-and-android-logcat-42-.pdf
nasrabadiam
 
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 (UA)
Parallel programming patterns (UA)Parallel programming patterns (UA)
Parallel programming patterns (UA)
Oleksandr Pavlyshak
 
Parallel programming patterns - Олександр Павлишак
Parallel programming patterns - Олександр ПавлишакParallel programming patterns - Олександр Павлишак
Parallel programming patterns - Олександр Павлишак
Igor Bronovskyy
 
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
 
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
 
MultiThreading-in-system-and-android-logcat-42-.pdf
MultiThreading-in-system-and-android-logcat-42-.pdfMultiThreading-in-system-and-android-logcat-42-.pdf
MultiThreading-in-system-and-android-logcat-42-.pdf
nasrabadiam
 
Node js
Node jsNode js
Node js
hazzaz
 
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
 
Parallel programming patterns (UA)
Parallel programming patterns (UA)Parallel programming patterns (UA)
Parallel programming patterns (UA)
Oleksandr Pavlyshak
 
Parallel programming patterns - Олександр Павлишак
Parallel programming patterns - Олександр ПавлишакParallel programming patterns - Олександр Павлишак
Parallel programming patterns - Олександр Павлишак
Igor Bronovskyy
 
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
 
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
 
Ad

Recently uploaded (20)

Linux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdfLinux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdf
RHCSA Guru
 
Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025
Splunk
 
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Impelsys Inc.
 
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdfThe Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
Abi john
 
Procurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptxProcurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptx
Jon Hansen
 
Electronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploitElectronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploit
niftliyevhuseyn
 
Generative Artificial Intelligence (GenAI) in Business
Generative Artificial Intelligence (GenAI) in BusinessGenerative Artificial Intelligence (GenAI) in Business
Generative Artificial Intelligence (GenAI) in Business
Dr. Tathagat Varma
 
tecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdftecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdf
fjgm517
 
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes
 
HCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser EnvironmentsHCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser Environments
panagenda
 
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-UmgebungenHCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
panagenda
 
Technology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data AnalyticsTechnology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data Analytics
InData Labs
 
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
BookNet Canada
 
How analogue intelligence complements AI
How analogue intelligence complements AIHow analogue intelligence complements AI
How analogue intelligence complements AI
Paul Rowe
 
AI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global TrendsAI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global Trends
InData Labs
 
Heap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and DeletionHeap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and Deletion
Jaydeep Kale
 
Build Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For DevsBuild Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For Devs
Brian McKeiver
 
How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?
Daniel Lehner
 
Role of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered ManufacturingRole of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered Manufacturing
Andrew Leo
 
Quantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur MorganQuantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur Morgan
Arthur Morgan
 
Linux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdfLinux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdf
RHCSA Guru
 
Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025
Splunk
 
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Impelsys Inc.
 
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdfThe Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
Abi john
 
Procurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptxProcurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptx
Jon Hansen
 
Electronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploitElectronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploit
niftliyevhuseyn
 
Generative Artificial Intelligence (GenAI) in Business
Generative Artificial Intelligence (GenAI) in BusinessGenerative Artificial Intelligence (GenAI) in Business
Generative Artificial Intelligence (GenAI) in Business
Dr. Tathagat Varma
 
tecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdftecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdf
fjgm517
 
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes
 
HCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser EnvironmentsHCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser Environments
panagenda
 
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-UmgebungenHCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
panagenda
 
Technology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data AnalyticsTechnology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data Analytics
InData Labs
 
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
BookNet Canada
 
How analogue intelligence complements AI
How analogue intelligence complements AIHow analogue intelligence complements AI
How analogue intelligence complements AI
Paul Rowe
 
AI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global TrendsAI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global Trends
InData Labs
 
Heap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and DeletionHeap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and Deletion
Jaydeep Kale
 
Build Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For DevsBuild Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For Devs
Brian McKeiver
 
How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?
Daniel Lehner
 
Role of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered ManufacturingRole of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered Manufacturing
Andrew Leo
 
Quantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur MorganQuantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur Morgan
Arthur Morgan
 
Ad

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