SlideShare a Scribd company logo
1 of 69
Ruby 1.9 Fibers
Cooperative Multi-Processing and Elegant Event-Driven
                    Programming



                   Kevin Ball
               Co-Founder and CTO
              fashioningchange.com
               kball@fashioningchange.com
                http://twitter.com/kbal11
Outline
• Multi-Processing Overview
• Ruby Fibers
• Event Driven Programming
• Fibers + Events => Ruby FTW
Multi-Processing
• Processes
• Threads
• Fibers
• Events
Processes

   • Independent (no shared
     state)
   • Interact via message
     passing if at all
   • Preemptively scheduled
   • Fairly heavyweight
Why Processes?
Why Processes?
• OS managed
Why Processes?
• OS managed
• Task-level parallelism
Why Processes?
• OS managed
• Task-level parallelism
• Great for embarrassingly parallel (IE web)
Threads
• Shared Data
• Fairly lightweight
• Also Preemptively Scheduled
Why Threading?
Why Threading?
• Resource Utilization
Why Threading?
• Resource Utilization
• Asynchronous I/O
Why Threading?
• Resource Utilization
• Asynchronous I/O
• Shared Data or Tight Coupling
Why Threading?
• Resource Utilization
• Asynchronous I/O
• Shared Data or Tight Coupling
• Good for fine-grained parallelism
Threading Problems
Threading Problems
Threading Problems
Threading Problems

         • Race conditions
         • Contention
         • Deadlocks
Fibers
Fibers
• Pauseable/Resumable
  Code Blocks
Fibers
• Pauseable/Resumable
  Code Blocks
• Very lightweight
Fibers
• Pauseable/Resumable
  Code Blocks
• Very lightweight
• Cooperatively scheduled
How Lightweight?
How Lightweight?

                  Threads     Fibers

 Time to create
                  1.14 sec   0.103 sec
    10,000
Memory for 1000
                  20.6M        3.3M
 Simultaneous
Cooperative Scheduling
Cooperative Scheduling
          • Explicit yielding and
            resuming
Cooperative Scheduling
          • Explicit yielding and
            resuming
          • No races or need for
            locks
Example: Fibonacci
fib = Fiber.new do
  f1 = f2 = 1
  loop do
    Fiber.yield f1
    f1, f2 = f2, f1 + f2
  end
end

5.times { puts fib.resume }
Example: Fibonacci
fib = Fiber.new do
  f1 = f2 = 1
  loop do
    Fiber.yield f1
    f1, f2 = f2, f1 + f2
  end
end

5.times { puts fib.resume }

1
1
2
3
5
Implicit Objects
fib = Fiber.new do
  f1 = f2 = 1
  loop do
    Fiber.yield f1
    f1, f2 = f2, f1 + f2
  end
end

5.times { puts fib.resume }
Implicit Objects
fib = Fiber.new do            fib = Object.new
  f1 = f2 = 1                 fib.instance_eval do
  loop do                       @f1 = @f2 = 1;
    Fiber.yield f1              def next
    f1, f2 = f2, f1 + f2          @old = @f1
  end                             @f1, @f2 = @f1, @f2, @f1 + @f2
end                               @old
                                end
5.times { puts fib.resume }   end

                              5.times { puts fib.next }
Why Bother?
Why Bother?

Aren’t blocks just implicit functions?
Why Bother?

  Aren’t blocks just implicit functions?


Changing the semantics changes the game.
Why Bother?

  Aren’t blocks just implicit functions?


Changing the semantics changes the game.

  Fibers have more flexible entry points
Synchronous
Asynchronicity
Synchronous
Asynchronicity
Have your asynchronous cake
       and eat it too!
Synchronous
           Asynchronicity
Write code that looks like
  puts "Setting up HTTP request #1"
  data = async_fetch('http://www.google.com/')
  puts "Fetched page #1: #{data.response_header.status}"




                           *Example from http://www.igvita.com/2009/05/13/fibers-cooperative-scheduling-in-ruby/
Synchronous
           Asynchronicity
Write code that looks like
  puts "Setting up HTTP request #1"
  data = async_fetch('http://www.google.com/')
  puts "Fetched page #1: #{data.response_header.status}"



Looks synchronous. Acts asynchronous.



                           *Example from http://www.igvita.com/2009/05/13/fibers-cooperative-scheduling-in-ruby/
Events: The Hot New Thing
Events: The Hot New Thing
  • Node.js
  • Twisted (python)
  • EventMachine
What Is Event-Driven
  Programming?
What Is Event-Driven
  Programming?
What Is Event-Driven
  Programming?
• Age-old Technique
What Is Event-Driven
  Programming?
• Age-old Technique
• Familiar to UI & Kernel Developers
What Is Event-Driven
  Programming?
• Age-old Technique
• Familiar to UI & Kernel Developers
• Control Flow determined by Events
What Is Event-Driven
  Programming?
• Age-old Technique
• Familiar to UI & Kernel Developers
• Control Flow determined by Events
• Callbacks the central construct
EventMachine Example
class Echo < EventMachine::Connection
  def post_init
    send_data 'Hello'
  end

  def receive_data(data)
    p data
  end
end

EventMachine.run {
  EventMachine.connect '127.0.0.1', 8081, Echo
}
The Downside?
The Downside?
 Deeply Nested Events
The Downside?
                          Deeply Nested Events

EventMachine.run {
  page = EventMachine::HttpRequest.new('http://google.ca/').get
  page.errback { p "Google is down! terminate?" }
  page.callback {
    about = EventMachine::HttpRequest.new('http://google.ca/search?q=eventmachine').get
    about.callback { # callback nesting, ad infinitum }
    about.errback { # error-handling code }
  }
}




                                          *Example from http://www.igvita.com/2010/03/22/untangling-evented-code-with-ruby-fibers/
The Solution? Fibers
The Solution? Fibers
def http_get(url)
  f = Fiber.current
  http = EventMachine::HttpRequest.new(url).get
 
  # resume fiber once http call is done
  http.callback { f.resume(http) }
  http.errback { f.resume(http) }
 
  return Fiber.yield
end




                           *Example from http://www.igvita.com/2010/03/22/untangling-evented-code-with-ruby-fibers/
The Solution? Fibers
def http_get(url)
  f = Fiber.current
  http = EventMachine::HttpRequest.new(url).get
 
  # resume fiber once http call is done
  http.callback { f.resume(http) }
  http.errback { f.resume(http) }
 
  return Fiber.yield
end


 
EventMachine.run do
  Fiber.new{
    page = http_get('http://www.google.com/')
    puts "Fetched page: #{page.response_header.status}"
 
    page = http_get('http://www.google.com/search?q=eventmachine')
    puts "Fetched page 2: #{page.response_header.status}"
  }.resume
end


                           *Example from http://www.igvita.com/2010/03/22/untangling-evented-code-with-ruby-fibers/
Still ugly, but...
Still ugly, but...


• You can wrap it up in a library
Still ugly, but...


• You can wrap it up in a library
• In fact, someone already did
Still ugly, but...


• You can wrap it up in a library
• In fact, someone already did
• gem install em-synchrony
Em-Synchrony Example
require   'rubygems'
require   'eventmachine'
require   'em-synchrony'
require   'em-synchrony/em-http'

EventMachine.synchrony do
  page = EventMachine::HttpRequest.new("http://www.google.com").get
 
  p "Look Ma! No callbacks! Fetched page: #{page}"
  EventMachine.stop
end
Where is it going?
Where is it going?

• Rails 3.1 Automatic Flushing
Where is it going?

• Rails 3.1 Automatic Flushing
• Goliath Webserver
Where is it going?

• Rails 3.1 Automatic Flushing
• Goliath Webserver
• Async Rails
Ruby FTW
Ruby FTW

  • Event-based architectures are
    winning
Ruby FTW

  • Event-based architectures are
    winning
  • Fibers => Events - Drawbacks
Ruby FTW

  • Event-based architectures are
    winning
  • Fibers => Events - Drawbacks
  • WIN!
More Resources
• http://ruby-doc.org/core-1.9/classes/
  Fiber.html
• http://www.igvita.com/
• https://github.com/eventmachine/
  eventmachine
Thank You!

     Kevin Ball
 Co-Founder and CTO
fashioningchange.com
 kball@fashioningchange.com
  http://twitter.com/kbal11

More Related Content

What's hot

0-60 with Goliath: High performance web services
0-60 with Goliath: High performance web services0-60 with Goliath: High performance web services
0-60 with Goliath: High performance web services
Ilya Grigorik
 
Cooking a rabbit pie
Cooking a rabbit pieCooking a rabbit pie
Cooking a rabbit pie
Tomas Doran
 

What's hot (20)

Communication in Python and the C10k problem
Communication in Python and the C10k problemCommunication in Python and the C10k problem
Communication in Python and the C10k problem
 
Dissecting the rabbit: RabbitMQ Internal Architecture
Dissecting the rabbit: RabbitMQ Internal ArchitectureDissecting the rabbit: RabbitMQ Internal Architecture
Dissecting the rabbit: RabbitMQ Internal Architecture
 
0-60 with Goliath: High performance web services
0-60 with Goliath: High performance web services0-60 with Goliath: High performance web services
0-60 with Goliath: High performance web services
 
Complex Made Simple: Sleep Better with TorqueBox
Complex Made Simple: Sleep Better with TorqueBoxComplex Made Simple: Sleep Better with TorqueBox
Complex Made Simple: Sleep Better with TorqueBox
 
Devignition 2011
Devignition 2011Devignition 2011
Devignition 2011
 
Concurrency in Python
Concurrency in PythonConcurrency in Python
Concurrency in Python
 
TorqueBox for Rubyists
TorqueBox for RubyistsTorqueBox for Rubyists
TorqueBox for Rubyists
 
TorqueBox: The beauty of Ruby with the power of JBoss. Presented at Devnexus...
TorqueBox: The beauty of Ruby with the power of JBoss.  Presented at Devnexus...TorqueBox: The beauty of Ruby with the power of JBoss.  Presented at Devnexus...
TorqueBox: The beauty of Ruby with the power of JBoss. Presented at Devnexus...
 
Queue your work
Queue your workQueue your work
Queue your work
 
Cooking a rabbit pie
Cooking a rabbit pieCooking a rabbit pie
Cooking a rabbit pie
 
Scaling application with RabbitMQ
Scaling application with RabbitMQScaling application with RabbitMQ
Scaling application with RabbitMQ
 
Faster PHP apps using Queues and Workers
Faster PHP apps using Queues and WorkersFaster PHP apps using Queues and Workers
Faster PHP apps using Queues and Workers
 
TorqueBox at DC:JBUG - November 2011
TorqueBox at DC:JBUG - November 2011TorqueBox at DC:JBUG - November 2011
TorqueBox at DC:JBUG - November 2011
 
Introduction to Python Celery
Introduction to Python CeleryIntroduction to Python Celery
Introduction to Python Celery
 
The details of CI/CD environment for Ruby
The details of CI/CD environment for RubyThe details of CI/CD environment for Ruby
The details of CI/CD environment for Ruby
 
Apache Camel in the belly of the Docker whale
Apache Camel in the belly of the Docker whaleApache Camel in the belly of the Docker whale
Apache Camel in the belly of the Docker whale
 
Handling 10k requests per second with Symfony and Varnish - SymfonyCon Berlin...
Handling 10k requests per second with Symfony and Varnish - SymfonyCon Berlin...Handling 10k requests per second with Symfony and Varnish - SymfonyCon Berlin...
Handling 10k requests per second with Symfony and Varnish - SymfonyCon Berlin...
 
About Node.js
About Node.jsAbout Node.js
About Node.js
 
A complete guide to Node.js
A complete guide to Node.jsA complete guide to Node.js
A complete guide to Node.js
 
Cachopo - Scalable Stateful Services - Madrid Elixir Meetup
Cachopo - Scalable Stateful Services - Madrid Elixir MeetupCachopo - Scalable Stateful Services - Madrid Elixir Meetup
Cachopo - Scalable Stateful Services - Madrid Elixir Meetup
 

Similar to Ruby 1.9 Fibers

SXSW 2012 JavaScript MythBusters
SXSW 2012 JavaScript MythBustersSXSW 2012 JavaScript MythBusters
SXSW 2012 JavaScript MythBusters
Elena-Oana Tabaranu
 
Ruby v cpp_preso
Ruby v cpp_presoRuby v cpp_preso
Ruby v cpp_preso
jessicard
 
Torquebox OSCON Java 2011
Torquebox OSCON Java 2011Torquebox OSCON Java 2011
Torquebox OSCON Java 2011
tobiascrawley
 

Similar to Ruby 1.9 Fibers (20)

Ruby's Concurrency Management: Now and Future
Ruby's Concurrency Management: Now and FutureRuby's Concurrency Management: Now and Future
Ruby's Concurrency Management: Now and Future
 
Ruby performance - The low hanging fruit
Ruby performance - The low hanging fruitRuby performance - The low hanging fruit
Ruby performance - The low hanging fruit
 
Concurrency in ruby
Concurrency in rubyConcurrency in ruby
Concurrency in ruby
 
Fiber in the 10th year
Fiber in the 10th yearFiber in the 10th year
Fiber in the 10th year
 
Fiber in the 10th year
Fiber in the 10th yearFiber in the 10th year
Fiber in the 10th year
 
Lessons Learnt in 2009
Lessons Learnt in 2009Lessons Learnt in 2009
Lessons Learnt in 2009
 
WTF is Twisted?
WTF is Twisted?WTF is Twisted?
WTF is Twisted?
 
C# Async/Await Explained
C# Async/Await ExplainedC# Async/Await Explained
C# Async/Await Explained
 
SXSW 2012 JavaScript MythBusters
SXSW 2012 JavaScript MythBustersSXSW 2012 JavaScript MythBusters
SXSW 2012 JavaScript MythBusters
 
Ruby v cpp_preso
Ruby v cpp_presoRuby v cpp_preso
Ruby v cpp_preso
 
50 EJB 3 Best Practices in 50 Minutes - JavaOne 2014
50 EJB 3 Best Practices in 50 Minutes - JavaOne 201450 EJB 3 Best Practices in 50 Minutes - JavaOne 2014
50 EJB 3 Best Practices in 50 Minutes - JavaOne 2014
 
Concurrent Programming Using the Disruptor
Concurrent Programming Using the DisruptorConcurrent Programming Using the Disruptor
Concurrent Programming Using the Disruptor
 
JS Event Loop
JS Event LoopJS Event Loop
JS Event Loop
 
Bringing Concurrency to Ruby - RubyConf India 2014
Bringing Concurrency to Ruby - RubyConf India 2014Bringing Concurrency to Ruby - RubyConf India 2014
Bringing Concurrency to Ruby - RubyConf India 2014
 
Python, async web frameworks, and MongoDB
Python, async web frameworks, and MongoDBPython, async web frameworks, and MongoDB
Python, async web frameworks, and MongoDB
 
parallel-asynchronous-programming-java.pptx
parallel-asynchronous-programming-java.pptxparallel-asynchronous-programming-java.pptx
parallel-asynchronous-programming-java.pptx
 
Torquebox OSCON Java 2011
Torquebox OSCON Java 2011Torquebox OSCON Java 2011
Torquebox OSCON Java 2011
 
Leveragong splunk for finding needle in the Haystack
Leveragong splunk for finding needle in the HaystackLeveragong splunk for finding needle in the Haystack
Leveragong splunk for finding needle in the Haystack
 
"Leveraging the Event Loop for Blazing-Fast Applications!", Michael Di Prisco
"Leveraging the Event Loop for Blazing-Fast Applications!",  Michael Di Prisco"Leveraging the Event Loop for Blazing-Fast Applications!",  Michael Di Prisco
"Leveraging the Event Loop for Blazing-Fast Applications!", Michael Di Prisco
 
Multithread Your Application
Multithread Your ApplicationMultithread Your Application
Multithread Your Application
 

More from Kevin Ball (7)

Flexible UI Components for a Multi-Framework World
Flexible UI Components for a Multi-Framework WorldFlexible UI Components for a Multi-Framework World
Flexible UI Components for a Multi-Framework World
 
Modern javascript
Modern javascriptModern javascript
Modern javascript
 
Npm Shrinkwrap
Npm ShrinkwrapNpm Shrinkwrap
Npm Shrinkwrap
 
Understanding the Nesting Structure of the Ember.js View Layer
Understanding the Nesting Structure of the Ember.js View LayerUnderstanding the Nesting Structure of the Ember.js View Layer
Understanding the Nesting Structure of the Ember.js View Layer
 
Intro to Javascript
Intro to JavascriptIntro to Javascript
Intro to Javascript
 
Underscore.js
Underscore.jsUnderscore.js
Underscore.js
 
Omniauth: Future Proof Your Authentication
Omniauth: Future Proof Your AuthenticationOmniauth: Future Proof Your Authentication
Omniauth: Future Proof Your Authentication
 

Recently uploaded

EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
Earley Information Science
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
giselly40
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
Enterprise Knowledge
 

Recently uploaded (20)

Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdf
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 

Ruby 1.9 Fibers

Editor's Notes

  1. \n
  2. \n
  3. \n
  4. \n
  5. \n
  6. \n
  7. \n
  8. \n
  9. \n
  10. \n
  11. \n
  12. \n
  13. \n
  14. \n
  15. \n
  16. \n
  17. \n
  18. \n
  19. \n
  20. \n
  21. \n
  22. \n
  23. \n
  24. \n
  25. \n
  26. \n
  27. \n
  28. \n
  29. \n
  30. \n
  31. \n
  32. \n
  33. \n
  34. \n
  35. \n
  36. \n
  37. \n
  38. \n
  39. \n
  40. \n
  41. \n
  42. \n
  43. \n
  44. \n
  45. \n
  46. \n
  47. \n
  48. \n
  49. \n
  50. \n
  51. \n
  52. \n
  53. \n
  54. \n
  55. \n
  56. \n
  57. \n
  58. \n
  59. \n
  60. \n
  61. \n
  62. \n
  63. \n
  64. \n
  65. \n
  66. \n
  67. \n
  68. \n
  69. \n