SlideShare a Scribd company logo
Threads in Ruby
What is a Thread?
• A thread is a light-weight process.
• Threads that belong to the same process share that process’s
resources.
Threads in Ruby
Threads in Ruby
Example 1
def add(arr)
sleep(2)
sum = 0
arr.each { |item| sum += item }
sum
end
@arr1 = [1, 2, 3]
@arr2 = [4, 5, 6]
@arr3 = [7, 8, 9]
puts "arr1 = #{add(@arr1)}"
puts "arr2 = #{add(@arr2)}"
puts "arr3 = #{add(@arr3)}"
Threads in Ruby
Output :
varun@kiprosh-varun:~/projects/test$ time ruby threads.rb
arr1 = 6
arr2 = 15
arr3 = 24
real 0m6.039s
user0m0.032s
sys 0m0.004s
Threads in Ruby
Example 2
def add(arr)
sleep(2)
sum = 0
arr.each { |item| sum += item }
sum
end
@arr1 = [1, 2, 3]
@arr2 = [4, 5, 6]
@arr3 = [7, 8, 9]
threads = (1..3).map do |i|
Thread.new(i) do |i|
arr = instance_variable_get("@arr#{i}")
puts "arr#{i} = #{add(arr)}"
end
end
threads.each { |t| t.join }
Threads in Ruby
Output :
varun@kiprosh-varun:~/projects/test$ time ruby test.rb
arr1 = 6
arr2 = 15
arr3 = 24
real 0m2.035s
user0m0.032s
sys 0m0.000s
varun@kiprosh-varun:~/projects/test$ time ruby test.rb
arr2 = 15
arr3 = 24
arr1 = 6
real 0m2.038s
user0m0.020s
sys 0m0.020s
Race Condition
Race Condition
Example 3
class Item
class << self; attr_accessor :price end
@price = 0
end
(1..10).each { Item.price += 10 }
puts "Item.price = #{Item.price}“
Output :
varun@kiprosh-varun:~/projects/test$ ruby test.rb
Item.price = 100
Race Condition
Example 4
class Item
class << self; attr_accessor :price end
@price = 0
end
threads = (1..10).map do |i|
Thread.new(i) do |i|
item_price = Item.price # Reading value
sleep(rand(0..2))
item_price += 10
# Updating value
sleep(rand(0..2))
Item.price = item_price # Writing value
end
end
threads.each {|t| t.join}
puts "Item.price = #{Item.price}“
Race Condition
Output :
varun@kiprosh-varun:~/projects/test$ ruby test.rb
Item.price = 20
varun@kiprosh-varun:~/projects/test$ ruby test.rb
Item.price = 30
varun@kiprosh-varun:~/projects/test$ ruby test.rb
Item.price = 10
Race Condition
The race condition is fundamentally due to the multi-step process of
changing a variable.
register = i
# read the current value from RAM into a register
register = register + 1 # increment it by one
i = register
# write the value back to the variable in RAM
●

OS can stop Thread 1 and start executing Thread 2 at any point in time.
Race Condition
i=0
# OS is running Thread 1
register = i # 0
register = register + 1 # 1
# OS switches to Thread 2
register = i # 0
register = register + 1 # 1
i = register # 1
# Now OS switches back to Thread 1
i = register # 1
MUTEX
(Mutual Exclusion)
Mutual Exclusion
class Item
class << self; attr_accessor :price end
@price = 0
end
mutex = Mutex.new
threads = (1..10).map do |i|
Thread.new(i) do |i|
mutex.synchronize do
item_price = Item.price # Reading value
sleep(rand(0..2))
item_price += 10
# Updating value
sleep(rand(0..2))
Item.price = item_price # Writing value
end
end
end
threads.each {|t| t.join}
puts "Item.price = #{Item.price}"
Mutual Exclusion
Output :
varun@kiprosh-varun:~/projects/test$ ruby test.rb
Item.price = 100
varun@kiprosh-varun:~/projects/test$ ruby test.rb
Item.price = 100
Conclusion
●

avoid Thread.new – locks exponentially grow the complexity of codebase

●

Celluloid or girl_friday – better alternatives than mutex

●

JRuby, Rubinius

More Related Content

What's hot

竝行
竝行竝行
Operator_Overloaing_Type_Conversion_OOPC(C++)
Operator_Overloaing_Type_Conversion_OOPC(C++)Operator_Overloaing_Type_Conversion_OOPC(C++)
Operator_Overloaing_Type_Conversion_OOPC(C++)
Yaksh Jethva
 
Javascript
JavascriptJavascript
Javascript
Tarek Raihan
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
Shubham Vishwambhar
 
Declarative JavaScript concepts and implemetation
Declarative JavaScript concepts and implemetationDeclarative JavaScript concepts and implemetation
Declarative JavaScript concepts and implemetation
Om Shankar
 
Lecture5
Lecture5Lecture5
Lecture5
ravifeelings
 
Scala + WattzOn, sitting in a tree....
Scala + WattzOn, sitting in a tree....Scala + WattzOn, sitting in a tree....
Scala + WattzOn, sitting in a tree....
Raffi Krikorian
 
Overloading
OverloadingOverloading
Overloading
poonamchopra7975
 
Fork Join (BeJUG 2012)
Fork Join (BeJUG 2012)Fork Join (BeJUG 2012)
Fork Join (BeJUG 2012)
Sander Mak (@Sander_Mak)
 
Good news, everybody! Guile 2.2 performance notes (FOSDEM 2016)
Good news, everybody! Guile 2.2 performance notes (FOSDEM 2016)Good news, everybody! Guile 2.2 performance notes (FOSDEM 2016)
Good news, everybody! Guile 2.2 performance notes (FOSDEM 2016)
Igalia
 
Bca 2nd sem u-4 operator overloading
Bca 2nd sem u-4 operator overloadingBca 2nd sem u-4 operator overloading
Bca 2nd sem u-4 operator overloading
Rai University
 
Custom Parameters in Hadoop Using Map Reduce
Custom Parameters in Hadoop Using Map ReduceCustom Parameters in Hadoop Using Map Reduce
Custom Parameters in Hadoop Using Map Reduce
FinTechopedia
 
Fork/Join for Fun and Profit!
Fork/Join for Fun and Profit!Fork/Join for Fun and Profit!
Fork/Join for Fun and Profit!
Sander Mak (@Sander_Mak)
 
Gearman & PHP
Gearman & PHPGearman & PHP
Gearman & PHP
Nemanja Krivokapic
 
Currying in JavaScript
Currying in JavaScriptCurrying in JavaScript
Currying in JavaScript
Ideas2IT Technologies
 
Operator overloading and type conversion in cpp
Operator overloading and type conversion in cppOperator overloading and type conversion in cpp
Operator overloading and type conversion in cpp
rajshreemuthiah
 
An Introduction to Reactive Cocoa
An Introduction to Reactive CocoaAn Introduction to Reactive Cocoa
An Introduction to Reactive Cocoa
SmartLogic
 
Elixir at Evercam (By Milos Mosic)
Elixir at Evercam (By Milos Mosic)Elixir at Evercam (By Milos Mosic)
PHP Lecture 3 - Functions
PHP Lecture 3 - FunctionsPHP Lecture 3 - Functions
PHP Lecture 3 - Functions
Al-Mamun Sarkar
 
ReactiveCocoa Goodness - Part I of II
ReactiveCocoa Goodness - Part I of IIReactiveCocoa Goodness - Part I of II
ReactiveCocoa Goodness - Part I of II
manuelmaly
 

What's hot (20)

竝行
竝行竝行
竝行
 
Operator_Overloaing_Type_Conversion_OOPC(C++)
Operator_Overloaing_Type_Conversion_OOPC(C++)Operator_Overloaing_Type_Conversion_OOPC(C++)
Operator_Overloaing_Type_Conversion_OOPC(C++)
 
Javascript
JavascriptJavascript
Javascript
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
 
Declarative JavaScript concepts and implemetation
Declarative JavaScript concepts and implemetationDeclarative JavaScript concepts and implemetation
Declarative JavaScript concepts and implemetation
 
Lecture5
Lecture5Lecture5
Lecture5
 
Scala + WattzOn, sitting in a tree....
Scala + WattzOn, sitting in a tree....Scala + WattzOn, sitting in a tree....
Scala + WattzOn, sitting in a tree....
 
Overloading
OverloadingOverloading
Overloading
 
Fork Join (BeJUG 2012)
Fork Join (BeJUG 2012)Fork Join (BeJUG 2012)
Fork Join (BeJUG 2012)
 
Good news, everybody! Guile 2.2 performance notes (FOSDEM 2016)
Good news, everybody! Guile 2.2 performance notes (FOSDEM 2016)Good news, everybody! Guile 2.2 performance notes (FOSDEM 2016)
Good news, everybody! Guile 2.2 performance notes (FOSDEM 2016)
 
Bca 2nd sem u-4 operator overloading
Bca 2nd sem u-4 operator overloadingBca 2nd sem u-4 operator overloading
Bca 2nd sem u-4 operator overloading
 
Custom Parameters in Hadoop Using Map Reduce
Custom Parameters in Hadoop Using Map ReduceCustom Parameters in Hadoop Using Map Reduce
Custom Parameters in Hadoop Using Map Reduce
 
Fork/Join for Fun and Profit!
Fork/Join for Fun and Profit!Fork/Join for Fun and Profit!
Fork/Join for Fun and Profit!
 
Gearman & PHP
Gearman & PHPGearman & PHP
Gearman & PHP
 
Currying in JavaScript
Currying in JavaScriptCurrying in JavaScript
Currying in JavaScript
 
Operator overloading and type conversion in cpp
Operator overloading and type conversion in cppOperator overloading and type conversion in cpp
Operator overloading and type conversion in cpp
 
An Introduction to Reactive Cocoa
An Introduction to Reactive CocoaAn Introduction to Reactive Cocoa
An Introduction to Reactive Cocoa
 
Elixir at Evercam (By Milos Mosic)
Elixir at Evercam (By Milos Mosic)Elixir at Evercam (By Milos Mosic)
Elixir at Evercam (By Milos Mosic)
 
PHP Lecture 3 - Functions
PHP Lecture 3 - FunctionsPHP Lecture 3 - Functions
PHP Lecture 3 - Functions
 
ReactiveCocoa Goodness - Part I of II
ReactiveCocoa Goodness - Part I of IIReactiveCocoa Goodness - Part I of II
ReactiveCocoa Goodness - Part I of II
 

Viewers also liked

Ruby thread safety first
Ruby thread safety firstRuby thread safety first
Ruby thread safety first
Emily Stolfo
 
Concurrent Programming with Ruby and Tuple Spaces
Concurrent Programming with Ruby and Tuple SpacesConcurrent Programming with Ruby and Tuple Spaces
Concurrent Programming with Ruby and Tuple Spaces
luccastera
 
Threading and Concurrency in Ruby
Threading and Concurrency in RubyThreading and Concurrency in Ruby
Threading and Concurrency in Ruby
Tim Raymond
 
Treading the Rails with Ruby Shoes
Treading the Rails with Ruby ShoesTreading the Rails with Ruby Shoes
Treading the Rails with Ruby Shoes
Eleanor McHugh
 
Multi-threaded web crawler in Ruby
Multi-threaded web crawler in RubyMulti-threaded web crawler in Ruby
Multi-threaded web crawler in Ruby
Polcode
 
Actors and Threads
Actors and ThreadsActors and Threads
Actors and Threads
mperham
 
The Top Skills That Can Get You Hired in 2017
The Top Skills That Can Get You Hired in 2017The Top Skills That Can Get You Hired in 2017
The Top Skills That Can Get You Hired in 2017
LinkedIn
 

Viewers also liked (7)

Ruby thread safety first
Ruby thread safety firstRuby thread safety first
Ruby thread safety first
 
Concurrent Programming with Ruby and Tuple Spaces
Concurrent Programming with Ruby and Tuple SpacesConcurrent Programming with Ruby and Tuple Spaces
Concurrent Programming with Ruby and Tuple Spaces
 
Threading and Concurrency in Ruby
Threading and Concurrency in RubyThreading and Concurrency in Ruby
Threading and Concurrency in Ruby
 
Treading the Rails with Ruby Shoes
Treading the Rails with Ruby ShoesTreading the Rails with Ruby Shoes
Treading the Rails with Ruby Shoes
 
Multi-threaded web crawler in Ruby
Multi-threaded web crawler in RubyMulti-threaded web crawler in Ruby
Multi-threaded web crawler in Ruby
 
Actors and Threads
Actors and ThreadsActors and Threads
Actors and Threads
 
The Top Skills That Can Get You Hired in 2017
The Top Skills That Can Get You Hired in 2017The Top Skills That Can Get You Hired in 2017
The Top Skills That Can Get You Hired in 2017
 

Similar to Threads in Ruby (Basics)

JRuby @ Boulder Ruby
JRuby @ Boulder RubyJRuby @ Boulder Ruby
JRuby @ Boulder Ruby
Nick Sieger
 
Dataflow: Declarative concurrency in Ruby
Dataflow: Declarative concurrency in RubyDataflow: Declarative concurrency in Ruby
Dataflow: Declarative concurrency in Ruby
Larry Diehl
 
Fast Web Applications Development with Ruby on Rails on Oracle
Fast Web Applications Development with Ruby on Rails on OracleFast Web Applications Development with Ruby on Rails on Oracle
Fast Web Applications Development with Ruby on Rails on Oracle
Raimonds Simanovskis
 
TDC2016POA | Trilha Programacao Funcional - Ramda JS como alternativa a under...
TDC2016POA | Trilha Programacao Funcional - Ramda JS como alternativa a under...TDC2016POA | Trilha Programacao Funcional - Ramda JS como alternativa a under...
TDC2016POA | Trilha Programacao Funcional - Ramda JS como alternativa a under...
tdc-globalcode
 
Ramda, a functional JavaScript library
Ramda, a functional JavaScript libraryRamda, a functional JavaScript library
Ramda, a functional JavaScript library
Derek Willian Stavis
 
Attributes Unwrapped: Lessons under the surface of active record
Attributes Unwrapped: Lessons under the surface of active recordAttributes Unwrapped: Lessons under the surface of active record
Attributes Unwrapped: Lessons under the surface of active record
.toster
 
Migrating To Ruby1.9
Migrating To Ruby1.9Migrating To Ruby1.9
Migrating To Ruby1.9
tomaspavelka
 
PowerShell_LangRef_v3 (1).pdf
PowerShell_LangRef_v3 (1).pdfPowerShell_LangRef_v3 (1).pdf
PowerShell_LangRef_v3 (1).pdf
outcast96
 
An introduction to Ruby
An introduction to RubyAn introduction to Ruby
An introduction to Ruby
Wes Oldenbeuving
 
No Callbacks, No Threads - RailsConf 2010
No Callbacks, No Threads - RailsConf 2010No Callbacks, No Threads - RailsConf 2010
No Callbacks, No Threads - RailsConf 2010
Ilya Grigorik
 
Async and parallel patterns and application design - TechDays2013 NL
Async and parallel patterns and application design - TechDays2013 NLAsync and parallel patterns and application design - TechDays2013 NL
Async and parallel patterns and application design - TechDays2013 NL
Arie Leeuwesteijn
 
Rack Middleware
Rack MiddlewareRack Middleware
Rack Middleware
daviddollar
 
GeoGebra JavaScript CheatSheet
GeoGebra JavaScript CheatSheetGeoGebra JavaScript CheatSheet
GeoGebra JavaScript CheatSheet
Jose Perez
 
Ruby on Rails Intro
Ruby on Rails IntroRuby on Rails Intro
Ruby on Rails Intro
zhang tao
 
Asynchronous Orchestration DSL on squbs
Asynchronous Orchestration DSL on squbsAsynchronous Orchestration DSL on squbs
Asynchronous Orchestration DSL on squbs
Anil Gursel
 
Practical Testing of Ruby Core
Practical Testing of Ruby CorePractical Testing of Ruby Core
Practical Testing of Ruby Core
Hiroshi SHIBATA
 
Php my sql - functions - arrays - tutorial - programmerblog.net
Php my sql - functions - arrays - tutorial - programmerblog.netPhp my sql - functions - arrays - tutorial - programmerblog.net
Php my sql - functions - arrays - tutorial - programmerblog.net
Programmer Blog
 
Open MP cheet sheet
Open MP cheet sheetOpen MP cheet sheet
Open MP cheet sheet
Piyush Mittal
 
Functional Programming in Javascript - IL Tech Talks week
Functional Programming in Javascript - IL Tech Talks weekFunctional Programming in Javascript - IL Tech Talks week
Functional Programming in Javascript - IL Tech Talks week
yoavrubin
 
Use PEG to Write a Programming Language Parser
Use PEG to Write a Programming Language ParserUse PEG to Write a Programming Language Parser
Use PEG to Write a Programming Language Parser
Yodalee
 

Similar to Threads in Ruby (Basics) (20)

JRuby @ Boulder Ruby
JRuby @ Boulder RubyJRuby @ Boulder Ruby
JRuby @ Boulder Ruby
 
Dataflow: Declarative concurrency in Ruby
Dataflow: Declarative concurrency in RubyDataflow: Declarative concurrency in Ruby
Dataflow: Declarative concurrency in Ruby
 
Fast Web Applications Development with Ruby on Rails on Oracle
Fast Web Applications Development with Ruby on Rails on OracleFast Web Applications Development with Ruby on Rails on Oracle
Fast Web Applications Development with Ruby on Rails on Oracle
 
TDC2016POA | Trilha Programacao Funcional - Ramda JS como alternativa a under...
TDC2016POA | Trilha Programacao Funcional - Ramda JS como alternativa a under...TDC2016POA | Trilha Programacao Funcional - Ramda JS como alternativa a under...
TDC2016POA | Trilha Programacao Funcional - Ramda JS como alternativa a under...
 
Ramda, a functional JavaScript library
Ramda, a functional JavaScript libraryRamda, a functional JavaScript library
Ramda, a functional JavaScript library
 
Attributes Unwrapped: Lessons under the surface of active record
Attributes Unwrapped: Lessons under the surface of active recordAttributes Unwrapped: Lessons under the surface of active record
Attributes Unwrapped: Lessons under the surface of active record
 
Migrating To Ruby1.9
Migrating To Ruby1.9Migrating To Ruby1.9
Migrating To Ruby1.9
 
PowerShell_LangRef_v3 (1).pdf
PowerShell_LangRef_v3 (1).pdfPowerShell_LangRef_v3 (1).pdf
PowerShell_LangRef_v3 (1).pdf
 
An introduction to Ruby
An introduction to RubyAn introduction to Ruby
An introduction to Ruby
 
No Callbacks, No Threads - RailsConf 2010
No Callbacks, No Threads - RailsConf 2010No Callbacks, No Threads - RailsConf 2010
No Callbacks, No Threads - RailsConf 2010
 
Async and parallel patterns and application design - TechDays2013 NL
Async and parallel patterns and application design - TechDays2013 NLAsync and parallel patterns and application design - TechDays2013 NL
Async and parallel patterns and application design - TechDays2013 NL
 
Rack Middleware
Rack MiddlewareRack Middleware
Rack Middleware
 
GeoGebra JavaScript CheatSheet
GeoGebra JavaScript CheatSheetGeoGebra JavaScript CheatSheet
GeoGebra JavaScript CheatSheet
 
Ruby on Rails Intro
Ruby on Rails IntroRuby on Rails Intro
Ruby on Rails Intro
 
Asynchronous Orchestration DSL on squbs
Asynchronous Orchestration DSL on squbsAsynchronous Orchestration DSL on squbs
Asynchronous Orchestration DSL on squbs
 
Practical Testing of Ruby Core
Practical Testing of Ruby CorePractical Testing of Ruby Core
Practical Testing of Ruby Core
 
Php my sql - functions - arrays - tutorial - programmerblog.net
Php my sql - functions - arrays - tutorial - programmerblog.netPhp my sql - functions - arrays - tutorial - programmerblog.net
Php my sql - functions - arrays - tutorial - programmerblog.net
 
Open MP cheet sheet
Open MP cheet sheetOpen MP cheet sheet
Open MP cheet sheet
 
Functional Programming in Javascript - IL Tech Talks week
Functional Programming in Javascript - IL Tech Talks weekFunctional Programming in Javascript - IL Tech Talks week
Functional Programming in Javascript - IL Tech Talks week
 
Use PEG to Write a Programming Language Parser
Use PEG to Write a Programming Language ParserUse PEG to Write a Programming Language Parser
Use PEG to Write a Programming Language Parser
 

Recently uploaded

GraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracyGraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracy
Tomaz Bratanic
 
“How Axelera AI Uses Digital Compute-in-memory to Deliver Fast and Energy-eff...
“How Axelera AI Uses Digital Compute-in-memory to Deliver Fast and Energy-eff...“How Axelera AI Uses Digital Compute-in-memory to Deliver Fast and Energy-eff...
“How Axelera AI Uses Digital Compute-in-memory to Deliver Fast and Energy-eff...
Edge AI and Vision Alliance
 
GraphRAG for LifeSciences Hands-On with the Clinical Knowledge Graph
GraphRAG for LifeSciences Hands-On with the Clinical Knowledge GraphGraphRAG for LifeSciences Hands-On with the Clinical Knowledge Graph
GraphRAG for LifeSciences Hands-On with the Clinical Knowledge Graph
Neo4j
 
Best 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERPBest 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERP
Pixlogix Infotech
 
Digital Banking in the Cloud: How Citizens Bank Unlocked Their Mainframe
Digital Banking in the Cloud: How Citizens Bank Unlocked Their MainframeDigital Banking in the Cloud: How Citizens Bank Unlocked Their Mainframe
Digital Banking in the Cloud: How Citizens Bank Unlocked Their Mainframe
Precisely
 
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-EfficiencyFreshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
ScyllaDB
 
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
saastr
 
Leveraging the Graph for Clinical Trials and Standards
Leveraging the Graph for Clinical Trials and StandardsLeveraging the Graph for Clinical Trials and Standards
Leveraging the Graph for Clinical Trials and Standards
Neo4j
 
Choosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptxChoosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptx
Brandon Minnick, MBA
 
Apps Break Data
Apps Break DataApps Break Data
Apps Break Data
Ivo Velitchkov
 
Biomedical Knowledge Graphs for Data Scientists and Bioinformaticians
Biomedical Knowledge Graphs for Data Scientists and BioinformaticiansBiomedical Knowledge Graphs for Data Scientists and Bioinformaticians
Biomedical Knowledge Graphs for Data Scientists and Bioinformaticians
Neo4j
 
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
Edge AI and Vision Alliance
 
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAUHCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
panagenda
 
JavaLand 2024: Application Development Green Masterplan
JavaLand 2024: Application Development Green MasterplanJavaLand 2024: Application Development Green Masterplan
JavaLand 2024: Application Development Green Masterplan
Miro Wengner
 
Public CyberSecurity Awareness Presentation 2024.pptx
Public CyberSecurity Awareness Presentation 2024.pptxPublic CyberSecurity Awareness Presentation 2024.pptx
Public CyberSecurity Awareness Presentation 2024.pptx
marufrahmanstratejm
 
5th LF Energy Power Grid Model Meet-up Slides
5th LF Energy Power Grid Model Meet-up Slides5th LF Energy Power Grid Model Meet-up Slides
5th LF Energy Power Grid Model Meet-up Slides
DanBrown980551
 
Astute Business Solutions | Oracle Cloud Partner |
Astute Business Solutions | Oracle Cloud Partner |Astute Business Solutions | Oracle Cloud Partner |
Astute Business Solutions | Oracle Cloud Partner |
AstuteBusiness
 
9 CEO's who hit $100m ARR Share Their Top Growth Tactics Nathan Latka, Founde...
9 CEO's who hit $100m ARR Share Their Top Growth Tactics Nathan Latka, Founde...9 CEO's who hit $100m ARR Share Their Top Growth Tactics Nathan Latka, Founde...
9 CEO's who hit $100m ARR Share Their Top Growth Tactics Nathan Latka, Founde...
saastr
 
Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)
Jakub Marek
 
Programming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup SlidesProgramming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup Slides
Zilliz
 

Recently uploaded (20)

GraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracyGraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracy
 
“How Axelera AI Uses Digital Compute-in-memory to Deliver Fast and Energy-eff...
“How Axelera AI Uses Digital Compute-in-memory to Deliver Fast and Energy-eff...“How Axelera AI Uses Digital Compute-in-memory to Deliver Fast and Energy-eff...
“How Axelera AI Uses Digital Compute-in-memory to Deliver Fast and Energy-eff...
 
GraphRAG for LifeSciences Hands-On with the Clinical Knowledge Graph
GraphRAG for LifeSciences Hands-On with the Clinical Knowledge GraphGraphRAG for LifeSciences Hands-On with the Clinical Knowledge Graph
GraphRAG for LifeSciences Hands-On with the Clinical Knowledge Graph
 
Best 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERPBest 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERP
 
Digital Banking in the Cloud: How Citizens Bank Unlocked Their Mainframe
Digital Banking in the Cloud: How Citizens Bank Unlocked Their MainframeDigital Banking in the Cloud: How Citizens Bank Unlocked Their Mainframe
Digital Banking in the Cloud: How Citizens Bank Unlocked Their Mainframe
 
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-EfficiencyFreshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
 
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
 
Leveraging the Graph for Clinical Trials and Standards
Leveraging the Graph for Clinical Trials and StandardsLeveraging the Graph for Clinical Trials and Standards
Leveraging the Graph for Clinical Trials and Standards
 
Choosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptxChoosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptx
 
Apps Break Data
Apps Break DataApps Break Data
Apps Break Data
 
Biomedical Knowledge Graphs for Data Scientists and Bioinformaticians
Biomedical Knowledge Graphs for Data Scientists and BioinformaticiansBiomedical Knowledge Graphs for Data Scientists and Bioinformaticians
Biomedical Knowledge Graphs for Data Scientists and Bioinformaticians
 
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
 
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAUHCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
 
JavaLand 2024: Application Development Green Masterplan
JavaLand 2024: Application Development Green MasterplanJavaLand 2024: Application Development Green Masterplan
JavaLand 2024: Application Development Green Masterplan
 
Public CyberSecurity Awareness Presentation 2024.pptx
Public CyberSecurity Awareness Presentation 2024.pptxPublic CyberSecurity Awareness Presentation 2024.pptx
Public CyberSecurity Awareness Presentation 2024.pptx
 
5th LF Energy Power Grid Model Meet-up Slides
5th LF Energy Power Grid Model Meet-up Slides5th LF Energy Power Grid Model Meet-up Slides
5th LF Energy Power Grid Model Meet-up Slides
 
Astute Business Solutions | Oracle Cloud Partner |
Astute Business Solutions | Oracle Cloud Partner |Astute Business Solutions | Oracle Cloud Partner |
Astute Business Solutions | Oracle Cloud Partner |
 
9 CEO's who hit $100m ARR Share Their Top Growth Tactics Nathan Latka, Founde...
9 CEO's who hit $100m ARR Share Their Top Growth Tactics Nathan Latka, Founde...9 CEO's who hit $100m ARR Share Their Top Growth Tactics Nathan Latka, Founde...
9 CEO's who hit $100m ARR Share Their Top Growth Tactics Nathan Latka, Founde...
 
Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)
 
Programming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup SlidesProgramming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup Slides
 

Threads in Ruby (Basics)

  • 2. What is a Thread? • A thread is a light-weight process. • Threads that belong to the same process share that process’s resources.
  • 4. Threads in Ruby Example 1 def add(arr) sleep(2) sum = 0 arr.each { |item| sum += item } sum end @arr1 = [1, 2, 3] @arr2 = [4, 5, 6] @arr3 = [7, 8, 9] puts "arr1 = #{add(@arr1)}" puts "arr2 = #{add(@arr2)}" puts "arr3 = #{add(@arr3)}"
  • 5. Threads in Ruby Output : varun@kiprosh-varun:~/projects/test$ time ruby threads.rb arr1 = 6 arr2 = 15 arr3 = 24 real 0m6.039s user0m0.032s sys 0m0.004s
  • 6. Threads in Ruby Example 2 def add(arr) sleep(2) sum = 0 arr.each { |item| sum += item } sum end @arr1 = [1, 2, 3] @arr2 = [4, 5, 6] @arr3 = [7, 8, 9] threads = (1..3).map do |i| Thread.new(i) do |i| arr = instance_variable_get("@arr#{i}") puts "arr#{i} = #{add(arr)}" end end threads.each { |t| t.join }
  • 7. Threads in Ruby Output : varun@kiprosh-varun:~/projects/test$ time ruby test.rb arr1 = 6 arr2 = 15 arr3 = 24 real 0m2.035s user0m0.032s sys 0m0.000s varun@kiprosh-varun:~/projects/test$ time ruby test.rb arr2 = 15 arr3 = 24 arr1 = 6 real 0m2.038s user0m0.020s sys 0m0.020s
  • 9. Race Condition Example 3 class Item class << self; attr_accessor :price end @price = 0 end (1..10).each { Item.price += 10 } puts "Item.price = #{Item.price}“ Output : varun@kiprosh-varun:~/projects/test$ ruby test.rb Item.price = 100
  • 10. Race Condition Example 4 class Item class << self; attr_accessor :price end @price = 0 end threads = (1..10).map do |i| Thread.new(i) do |i| item_price = Item.price # Reading value sleep(rand(0..2)) item_price += 10 # Updating value sleep(rand(0..2)) Item.price = item_price # Writing value end end threads.each {|t| t.join} puts "Item.price = #{Item.price}“
  • 11. Race Condition Output : varun@kiprosh-varun:~/projects/test$ ruby test.rb Item.price = 20 varun@kiprosh-varun:~/projects/test$ ruby test.rb Item.price = 30 varun@kiprosh-varun:~/projects/test$ ruby test.rb Item.price = 10
  • 12. Race Condition The race condition is fundamentally due to the multi-step process of changing a variable. register = i # read the current value from RAM into a register register = register + 1 # increment it by one i = register # write the value back to the variable in RAM ● OS can stop Thread 1 and start executing Thread 2 at any point in time.
  • 13. Race Condition i=0 # OS is running Thread 1 register = i # 0 register = register + 1 # 1 # OS switches to Thread 2 register = i # 0 register = register + 1 # 1 i = register # 1 # Now OS switches back to Thread 1 i = register # 1
  • 15. Mutual Exclusion class Item class << self; attr_accessor :price end @price = 0 end mutex = Mutex.new threads = (1..10).map do |i| Thread.new(i) do |i| mutex.synchronize do item_price = Item.price # Reading value sleep(rand(0..2)) item_price += 10 # Updating value sleep(rand(0..2)) Item.price = item_price # Writing value end end end threads.each {|t| t.join} puts "Item.price = #{Item.price}"
  • 16. Mutual Exclusion Output : varun@kiprosh-varun:~/projects/test$ ruby test.rb Item.price = 100 varun@kiprosh-varun:~/projects/test$ ruby test.rb Item.price = 100
  • 17. Conclusion ● avoid Thread.new – locks exponentially grow the complexity of codebase ● Celluloid or girl_friday – better alternatives than mutex ● JRuby, Rubinius