SlideShare a Scribd company logo
1 of 17
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
 
Declarative JavaScript concepts and implemetation
Declarative JavaScript concepts and implemetationDeclarative JavaScript concepts and implemetation
Declarative JavaScript concepts and implemetationOm Shankar
 
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
 
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 overloadingRai 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 ReduceFinTechopedia
 
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 cpprajshreemuthiah
 
An Introduction to Reactive Cocoa
An Introduction to Reactive CocoaAn Introduction to Reactive Cocoa
An Introduction to Reactive CocoaSmartLogic
 
PHP Lecture 3 - Functions
PHP Lecture 3 - FunctionsPHP Lecture 3 - Functions
PHP Lecture 3 - FunctionsAl-Mamun Sarkar
 
ReactiveCocoa Goodness - Part I of II
ReactiveCocoa Goodness - Part I of IIReactiveCocoa Goodness - Part I of II
ReactiveCocoa Goodness - Part I of IImanuelmaly
 

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

[E lit] security solution biz. proposal v0.4.1 [자동 저장]
[E lit] security solution biz. proposal v0.4.1 [자동 저장][E lit] security solution biz. proposal v0.4.1 [자동 저장]
[E lit] security solution biz. proposal v0.4.1 [자동 저장]eLITeLIT
 
eLIT PEL-1000 RTLS proposal
eLIT PEL-1000 RTLS proposaleLIT PEL-1000 RTLS proposal
eLIT PEL-1000 RTLS proposaleLITeLIT
 
Practica n° 5
Practica n° 5Practica n° 5
Practica n° 5347356
 
2012 2013 dual enrollment info session
2012 2013 dual enrollment info session2012 2013 dual enrollment info session
2012 2013 dual enrollment info sessioncenterforcreativearts
 
[eLIT] Cambodia reference site
[eLIT] Cambodia reference site [eLIT] Cambodia reference site
[eLIT] Cambodia reference site eLITeLIT
 
elit Wirlesss Net. Solution
elit Wirlesss Net. Solutionelit Wirlesss Net. Solution
elit Wirlesss Net. SolutioneLITeLIT
 
LITBiz LBS, GIS Solution
LITBiz LBS, GIS SolutionLITBiz LBS, GIS Solution
LITBiz LBS, GIS SolutioneLITeLIT
 
Contoh kuesionerpenelitian
Contoh kuesionerpenelitianContoh kuesionerpenelitian
Contoh kuesionerpenelitianBintang Bless
 

Viewers also liked (17)

Secuencia
SecuenciaSecuencia
Secuencia
 
áLbum de fotografia
áLbum de fotografiaáLbum de fotografia
áLbum de fotografia
 
Encantamiento
EncantamientoEncantamiento
Encantamiento
 
[E lit] security solution biz. proposal v0.4.1 [자동 저장]
[E lit] security solution biz. proposal v0.4.1 [자동 저장][E lit] security solution biz. proposal v0.4.1 [자동 저장]
[E lit] security solution biz. proposal v0.4.1 [자동 저장]
 
eLIT PEL-1000 RTLS proposal
eLIT PEL-1000 RTLS proposaleLIT PEL-1000 RTLS proposal
eLIT PEL-1000 RTLS proposal
 
Dian andriani 2 d
Dian andriani 2 dDian andriani 2 d
Dian andriani 2 d
 
Practica n° 5
Practica n° 5Practica n° 5
Practica n° 5
 
Manual book sismul
Manual book sismulManual book sismul
Manual book sismul
 
Dian andriani 2 d
Dian andriani 2 dDian andriani 2 d
Dian andriani 2 d
 
2012 2013 dual enrollment info session
2012 2013 dual enrollment info session2012 2013 dual enrollment info session
2012 2013 dual enrollment info session
 
Sosiologi
SosiologiSosiologi
Sosiologi
 
[eLIT] Cambodia reference site
[eLIT] Cambodia reference site [eLIT] Cambodia reference site
[eLIT] Cambodia reference site
 
Sosiologi
SosiologiSosiologi
Sosiologi
 
elit Wirlesss Net. Solution
elit Wirlesss Net. Solutionelit Wirlesss Net. Solution
elit Wirlesss Net. Solution
 
LITBiz LBS, GIS Solution
LITBiz LBS, GIS SolutionLITBiz LBS, GIS Solution
LITBiz LBS, GIS Solution
 
Contoh kuesionerpenelitian
Contoh kuesionerpenelitianContoh kuesionerpenelitian
Contoh kuesionerpenelitian
 
IMUNOLOGIJJA
IMUNOLOGIJJAIMUNOLOGIJJA
IMUNOLOGIJJA
 

Similar to Threads

JRuby @ Boulder Ruby
JRuby @ Boulder RubyJRuby @ Boulder Ruby
JRuby @ Boulder RubyNick Sieger
 
Dataflow: Declarative concurrency in Ruby
Dataflow: Declarative concurrency in RubyDataflow: Declarative concurrency in Ruby
Dataflow: Declarative concurrency in RubyLarry 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 OracleRaimonds Simanovskis
 
Ramda, a functional JavaScript library
Ramda, a functional JavaScript libraryRamda, a functional JavaScript library
Ramda, a functional JavaScript libraryDerek Willian Stavis
 
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
 
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.9tomaspavelka
 
PowerShell_LangRef_v3 (1).pdf
PowerShell_LangRef_v3 (1).pdfPowerShell_LangRef_v3 (1).pdf
PowerShell_LangRef_v3 (1).pdfoutcast96
 
No Callbacks, No Threads - RailsConf 2010
No Callbacks, No Threads - RailsConf 2010No Callbacks, No Threads - RailsConf 2010
No Callbacks, No Threads - RailsConf 2010Ilya 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 NLArie Leeuwesteijn
 
GeoGebra JavaScript CheatSheet
GeoGebra JavaScript CheatSheetGeoGebra JavaScript CheatSheet
GeoGebra JavaScript CheatSheetJose Perez
 
Ruby on Rails Intro
Ruby on Rails IntroRuby on Rails Intro
Ruby on Rails Introzhang tao
 
Asynchronous Orchestration DSL on squbs
Asynchronous Orchestration DSL on squbsAsynchronous Orchestration DSL on squbs
Asynchronous Orchestration DSL on squbsAnil Gursel
 
Practical Testing of Ruby Core
Practical Testing of Ruby CorePractical Testing of Ruby Core
Practical Testing of Ruby CoreHiroshi 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.netProgrammer Blog
 
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 weekyoavrubin
 
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 ParserYodalee
 

Similar to Threads (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
 
Ramda, a functional JavaScript library
Ramda, a functional JavaScript libraryRamda, a functional JavaScript library
Ramda, a functional JavaScript library
 
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...
 
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
 

Threads

  • 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