Slide 1

Slide 1 text

Tony Arcieri MountainWest RubyConf March 15th, 2012 Concurrent programming with http://github.com/celluloid

Slide 2

Slide 2 text

About Me

Slide 3

Slide 3 text

About Me libev binding for Ruby (1 year before Node)

Slide 4

Slide 4 text

About Me Actors +“Fibered” I/O (2 years before em-synchrony)

Slide 5

Slide 5 text

About Me Ruby-Flavored Erlang (2 years before Elixir)

Slide 6

Slide 6 text

http://elixir-lang.org/

Slide 7

Slide 7 text

About Me Didn’t talk about Revactor or Reia at MWRC 2008

Slide 8

Slide 8 text

What next?

Slide 9

Slide 9 text

No content

Slide 10

Slide 10 text

No content

Slide 11

Slide 11 text

If I can’t drag Erlang halfway to Ruby...

Slide 12

Slide 12 text

Perhaps I can get Ruby halfway to Erlang...

Slide 13

Slide 13 text

Rubyists don’t like threads I want to change that

Slide 14

Slide 14 text

x86 CPU Trends (Not Entirely to Scale)

Slide 15

Slide 15 text

Multicore is the future

Slide 16

Slide 16 text

Threads are important

Slide 17

Slide 17 text

No GIL! Thread-level parallelism Rubinius Threads = Multicore

Slide 18

Slide 18 text

Parallel Blocking I/O But only one Ruby thread at a time :( YARV Threads != Multicore

Slide 19

Slide 19 text

When everyone has 100 core CPUs...

Slide 20

Slide 20 text

will we run 100 virtual machines?

Slide 21

Slide 21 text

or one?

Slide 22

Slide 22 text

Sidekiq What if 1 Sidekiq process could do the work of 20 Resque processes? http://mperham.github.com/sidekiq/

Slide 23

Slide 23 text

A little about Revactor...

Slide 24

Slide 24 text

Revactor predates: •Neverblock •Dramatis •Rack::FiberPool •em-synchrony

Slide 25

Slide 25 text

Inspired by: •Erlang •Omnibus Concurrency (MenTaLguY) •Kamaelia (Python) •Eventlet (Python)

Slide 26

Slide 26 text

Single-Threaded

Slide 27

Slide 27 text

Bad API

Slide 28

Slide 28 text

listener = Actor::TCP.listen(HOST, PORT, :filter => :line) puts "Listening on #{HOST}:#{PORT}" # The main loop handles incoming connections loop do # Spawn a new actor for each incoming connection Actor.spawn(listener.accept) do |sock| puts "#{sock.remote_addr}:#{sock.remote_port} connected" # Connection handshaking begin sock.write "Please enter a nickname:" nickname = sock.read server << T[:register, Actor.current, nickname] # Flip the socket into asynchronous "active" mode # This means the Actor can receive messages from # the socket alongside other events. sock.controller = Actor.current sock.active = :once # Main message loop loop do Actor.receive do |filter| filter.when(T[:tcp, sock]) do |_, _, message| server << T[:say, Actor.current, message] sock.active = :once end

Slide 29

Slide 29 text

WAT

Slide 30

Slide 30 text

No content

Slide 31

Slide 31 text

listener = Actor::TCP.listen(HOST, PORT, :filter => :line) puts "Listening on #{HOST}:#{PORT}" # The main loop handles incoming connections loop do # Spawn a new actor for each incoming connection Actor.spawn(listener.accept) do |sock| puts "#{sock.remote_addr}:#{sock.remote_port} connected" # Connection handshaking begin sock.write "Please enter a nickname:" nickname = sock.read server << T[:register, Actor.current, nickname] # Flip the socket into asynchronous "active" mode # This means the Actor can receive messages from # the socket alongside other events. sock.controller = Actor.current sock.active = :once # Main message loop loop do Actor.receive do |filter| filter.when(T[:tcp, sock]) do |_, _, message| server << T[:say, Actor.current, message] sock.active = :once end

Slide 32

Slide 32 text

Procedural!

Slide 33

Slide 33 text

Ugly!

Slide 34

Slide 34 text

WTF is T? filter.when(T[:tcp, sock]) do |_, _, message| server << T[:say, Actor.current, message] sock.active = :once end

Slide 35

Slide 35 text

Less Erlang

Slide 36

Slide 36 text

More Objects

Slide 37

Slide 37 text

Can We Do Better?

Slide 38

Slide 38 text

YES

Slide 39

Slide 39 text

What is Celluloid?

Slide 40

Slide 40 text

Celluloid is a general purpose concurrency framework for Ruby

Slide 41

Slide 41 text

A Contrived Example

Slide 42

Slide 42 text

require 'thread' class ConcurrentNestedHash def initialize @outer = {} @mutex = Mutex.new end def [](*keys) @mutex.synchronize { keys.inject(@outer) { |h,k| h[k] } } end def []=(*args) @mutex.synchronize do value = args.pop raise ArgumentError, "wrong number of arguments (1 for 2)" if args.empty? key = args.pop hash = args.inject(@outer) { |h,k| h[k] ||= {} } hash[key] = value end end def inspect; @mutex.synchronize { super }; end end

Slide 43

Slide 43 text

>> h = ConcurrentNestedHash.new => #> >> h[:foo, :bar, :baz] = 42 => 42 >> h => #{:bar=>{:baz=>42}}}, @mutex=#> >> h[:foo, :bar, :baz] => 42

Slide 44

Slide 44 text

-require 'thread' +require 'celluloid' class ConcurrentNestedHash + include Celluloid def initialize @outer = {} - @mutex = Mutex.new end def [](*keys) - @mutex.synchronize { keys.inject(@outer) { |h,k| h[k] } } + keys.inject(@outer) { |h,k| h[k] } end def []=(*args) - @mutex.synchronize do value = args.pop raise ArgumentError, "wrong number of arguments (1 for 2)" if args.empty? key = args.pop hash = args.inject(@outer) { |h,k| h[k] ||= {} } hash[key] = value - end end - - def inspect; @mutex.synchronize { super }; end end

Slide 45

Slide 45 text

require 'celluloid' class ConcurrentNestedHash include Celluloid def initialize @outer = {} end def [](*keys) keys.inject(@outer) { |h,k| h[k] } end def []=(*args) value = args.pop raise ArgumentError, "wrong number of arguments (1 for 2)" if args.empty? key = args.pop hash = args.inject(@outer) { |h,k| h[k] ||= {} } hash[key] = value end end

Slide 46

Slide 46 text

How?

Slide 47

Slide 47 text

MAGIC

Slide 48

Slide 48 text

Automatic locking?

Slide 49

Slide 49 text

No content

Slide 50

Slide 50 text

No content

Slide 51

Slide 51 text

Locks are hard •Dining Philosophers Problem •Sleeping Barber Problem •Cigarette Smokers Problem

Slide 52

Slide 52 text

OOP + Concurrency

Slide 53

Slide 53 text

“I thought of objects being like biological cells and/or individual computers on a network, only able to communicate with messages” - Alan Kay, creator of Smalltalk, on the meaning of "object oriented programming"

Slide 54

Slide 54 text

OOP Tools Classes Inheritance Messages

Slide 55

Slide 55 text

Concurrency Tools Threads Locks Queues

Slide 56

Slide 56 text

OOP Tools Classes Inheritance Messages Concurrency Tools Threads Locks Queues +

Slide 57

Slide 57 text

=

Slide 58

Slide 58 text

Concurrent Objects &DOOHU &HOOXORLG $FWRU3UR[\ &$// 5HFHLYHU &HOOXORLG 0DLOER[ 5(63216( &HOOXORLG 0DLOER[ &HOOXORLG$FWRU &HOOXORLG&DOO &HOOXORLG5HVSRQVH

Slide 59

Slide 59 text

Communicating Sequential Processes •Do One Thing At a Time •Communicate With Messages •Encapsulate Local State

Slide 60

Slide 60 text

Concurrent Objects do more...

Slide 61

Slide 61 text

Generalized Deadlock-free Synchronization

Slide 62

Slide 62 text

No content

Slide 63

Slide 63 text

No content

Slide 64

Slide 64 text

No content

Slide 65

Slide 65 text

No content

Slide 66

Slide 66 text

No content

Slide 67

Slide 67 text

Pythons did it!

Slide 68

Slide 68 text

No content

Slide 69

Slide 69 text

1997

Slide 70

Slide 70 text

No content

Slide 71

Slide 71 text

1999

Slide 72

Slide 72 text

No content

Slide 73

Slide 73 text

Web vs Objects (Not to Scale)

Slide 74

Slide 74 text

No content

Slide 75

Slide 75 text

How does Celluloid work?

Slide 76

Slide 76 text

>> h = ConcurrentNestedHash.new => #

Slide 77

Slide 77 text

>> h = ConcurrentNestedHash.new => #

Slide 78

Slide 78 text

# Class methods added to classes which include Celluloid module ClassMethods # Create a new actor def new(*args, &block) proxy = Actor.new(allocate).proxy proxy._send_(:initialize, *args, &block) proxy end ...

Slide 79

Slide 79 text

Synchronous Calls

Slide 80

Slide 80 text

EXTREME Late Binding &DOOHU &HOOXORLG $FWRU3UR[\ &$// 5HFHLYHU &HOOXORLG 0DLOER[ 5(63216( &HOOXORLG 0DLOER[ &HOOXORLG$FWRU &HOOXORLG&DOO &HOOXORLG5HVSRQVH

Slide 81

Slide 81 text

>> h = ConcurrentNestedHash.new => # >> h.inspect => “#” Synchronous Calls

Slide 82

Slide 82 text

Asynchronous Calls

Slide 83

Slide 83 text

Asynchronous Calls &DOOHU &HOOXORLG $FWRU3UR[\ &$// 5HFHLYHU &HOOXORLG 0DLOER[ &HOOXORLG$FWRU &HOOXORLG&DOO

Slide 84

Slide 84 text

Asynchronous Calls >> h = ConcurrentNestedHash.new => # >> h.send!(:[]=, :foo, :bar, :baz, 42) => nil >> h[:foo, :bar, :baz] => 42

Slide 85

Slide 85 text

>> h = ConcurrentNestedHash.new => # >> h.send!(:[]=, :foo, :bar, :baz, 42) => nil >> h[:foo, :bar, :baz] => 42 Asynchronous Calls

Slide 86

Slide 86 text

Asynchronous Calls >> h.inspect! => nil

Slide 87

Slide 87 text

Asynchronous Calls Kind of like “next tick”

Slide 88

Slide 88 text

Asynchronous Calls How do I get the value returned?

Slide 89

Slide 89 text

Futures

Slide 90

Slide 90 text

Futures &DOOHU &HOOXORLG $FWRU3UR[\ 5HFHLYHU &HOOXORLG 0DLOER[ &HOOXORLG$FWRU &HOOXORLG&DOO &$// &HOOXORLG 0DLOER[ )8785( &HOOXORLG )XWXUH &HOOXORLG5HVSRQVH 9$/8(" 9$/8(

Slide 91

Slide 91 text

>> h = ConcurrentNestedHash.new => # >> future = h.future :inspect => # >> 41 + 1 # roflscale computation => 42 >> future.value => “#” Futures

Slide 92

Slide 92 text

>> h = ConcurrentNestedHash.new => # >> future = h.future :inspect => # >> 41 + 1 # roflscale computation => 42 >> future.value => “#” Futures

Slide 93

Slide 93 text

Basic Ingredients •Regular method calls •Async calls (“next tick”) •Futures

Slide 94

Slide 94 text

Secret Sauce

Slide 95

Slide 95 text

How do we prevent deadlocks?

Slide 96

Slide 96 text

No content

Slide 97

Slide 97 text

No content

Slide 98

Slide 98 text

No content

Slide 99

Slide 99 text

No content

Slide 100

Slide 100 text

No content

Slide 101

Slide 101 text

Why do deadlocks happen?

Slide 102

Slide 102 text

Waiting for something that never happens...

Slide 103

Slide 103 text

...instead of what’s important

Slide 104

Slide 104 text

No content

Slide 105

Slide 105 text

How can we wait on everything at once?

Slide 106

Slide 106 text

FIBERS!

Slide 107

Slide 107 text

WAT?

Slide 108

Slide 108 text

No content

Slide 109

Slide 109 text

SUBLIMINAL MESSAGE: DONALD KNUTH IS YODA

Slide 110

Slide 110 text

No really...

Slide 111

Slide 111 text

Communicating Sequential Processes Do one thing at a time

Slide 112

Slide 112 text

Fibers Cheap suspendable/resumable execution context

Slide 113

Slide 113 text

Fibers Cheap suspendable/resumable execution context Communicating Sequential Processes Do one thing at a time +

Slide 114

Slide 114 text

Internal Concurrency for Actors

Slide 115

Slide 115 text

Don’t Block, Suspend to the Scheduler

Slide 116

Slide 116 text

Example!

Slide 117

Slide 117 text

require 'celluloid' class Person include Celluloid def name self.class.to_s end def greet(interested_party) "Hello #{interested_party.name}, I'm #{name}" end end class Joe < Person; end class Mike < Person def greet(other) super << "\n" << other.greet(current_actor) end end mike = Mike.new joe = Joe.new puts mike.greet(joe)

Slide 118

Slide 118 text

Hello Joe, I'm Mike Hello Mike, I'm Joe Output

Slide 119

Slide 119 text

No content

Slide 120

Slide 120 text

But it is a cool story!

Slide 121

Slide 121 text

Circular Call Graph 0LNH -RH JUHHW QDPH

Slide 122

Slide 122 text

Communicating Sequential Processes Do one thing at a time

Slide 123

Slide 123 text

DEADLOCK!

Slide 124

Slide 124 text

require 'celluloid' class Person include Celluloid def name self.class.to_s end def greet(interested_party) "Hello #{interested_party.name}, I'm #{name}" end end class Joe < Person; end class Mike < Person def greet(other) super << "\n" << other.greet(current_actor) end end mike = Mike.new joe = Joe.new puts mike.greet(joe)

Slide 125

Slide 125 text

0LNH -RH 0LNHJUHHW -RHJUHHW 0LNHQDPH J U H H W + H OO R 0 L N H J U H H W 0 L N H 6XVSHQGHG Multitasking Fibers

Slide 126

Slide 126 text

Waiting tasks suspend themselves so ready tasks can run

Slide 127

Slide 127 text

Every method call creates a Fiber

Slide 128

Slide 128 text

No content

Slide 129

Slide 129 text

Slow?

Slide 130

Slide 130 text

Call Benchmark Core i7 2.0GHz (OS X 10.7.3) Rubinius YARV 16815/s (60µs) - JRuby 1.6.7 20899/s (50µs) - JRuby HEAD 15260/s (65µs) - rbx HEAD 9367/s (107µs) - Ruby 1.9.3

Slide 131

Slide 131 text

No content

Slide 132

Slide 132 text

What if an actor crashes?

Slide 133

Slide 133 text

No content

Slide 134

Slide 134 text

No content

Slide 135

Slide 135 text

Fault Tolerance •Supervisors & Supervision Trees •“Fail early”, restart in a clean state •Do what Erlang does •No seriously, do what Erlang does

Slide 136

Slide 136 text

Evented I/O for Celluloid http://github.com/celluloid/celluloid-io

Slide 137

Slide 137 text

Now that we have threads licked... how about I/O?

Slide 138

Slide 138 text

USE BLOCKING I/O

Slide 139

Slide 139 text

Blocking IO is OK!* No central event loop to block

Slide 140

Slide 140 text

*But be careful Locks in external services = Deadlocks in Celluloid

Slide 141

Slide 141 text

But how will I serve my roflmillions of users?

Slide 142

Slide 142 text

Evented IO •Large numbers of connections (>1000) •Mostly idle connections •Mostly IO-bound problems •Websockets are an ideal case

Slide 143

Slide 143 text

Actors are event loops

Slide 144

Slide 144 text

&HOOXORLG $FWRU &HOOXORLG 0DLOER[ &RQGLWLRQ 9DULDEOH Normal Actors

Slide 145

Slide 145 text

Celluloid::IO Actors &HOOXORLG $FWRU &HOOXORLG ,20DLOER[ &HOOXORLG ,25HDFWRU

Slide 146

Slide 146 text

nio4r-powered reactor

Slide 147

Slide 147 text

nio4r •Quasi-inspired by Java NIO •Smallest API possible •libev C extension for CRuby/rbx •Java extension for JRuby •Pure Ruby version too! http://github.com/tarcieri/nio4r/

Slide 148

Slide 148 text

Celluloid::IO::TCPSocket •Uses fibered I/O •“Duck-type” of ::TCPSocket •Evented inside Celluloid::IO actors •Blocking IO elsewhere (Ruby Threads, normal Celluloid actors)

Slide 149

Slide 149 text

Evented IO AND Threaded IO You don’t have to choose!

Slide 150

Slide 150 text

Transparent handles you can pass around Kind of like file descriptors!

Slide 151

Slide 151 text

Other replacement classes •Celluloid::IO::TCPServer •Celluloid::IO::UDPSocket •No Celluloid::IO::UnixSocket yet, sorry :(

Slide 152

Slide 152 text

Echo Server Example

Slide 153

Slide 153 text

class EchoServer include Celluloid::IO def initialize(host, port) puts "*** Starting echo server on #{host}:#{port}" # Since we included Celluloid::IO, we're actually making a # Celluloid::IO::TCPServer here @server = TCPServer.new(host, port) run! end def finalize @server.close if @server end def run loop { handle_connection! @server.accept } end def handle_connection(socket) _, port, host = socket.peeraddr puts "*** Received connection from #{host}:#{port}" loop { socket.write socket.readpartial(4096) } rescue EOFError puts "*** #{host}:#{port} disconnected" socket.close end end supervisor = EchoServer.supervise("127.0.0.1", 1234) trap("INT") { supervisor.terminate; exit } sleep

Slide 154

Slide 154 text

7&36RFNHWEDVHG/LEUDULHV (YHQW0DFKLQH/LEUDULHV $6<1&$//7+(7+,1*6 ),%(5,=($//7+(7+,1*6 AAAHPV\QFKURQ\FRPSDWLEOH OLEUDULHV Running out of gas after slide #150

Slide 155

Slide 155 text

^^^ LET’S USE THIS 7&36RFNHWEDVHG/LEUDULHV

Slide 156

Slide 156 text

Dependency Injection

Slide 157

Slide 157 text

MyClient.new(‘myhost.domain’, 1234, :socket => Celluloid::IO::TCPSocket)

Slide 158

Slide 158 text

Easy Peasy!

Slide 159

Slide 159 text

Celluloid::IO-powered web server http://github.com/celluloid/reel

Slide 160

Slide 160 text

Hello World Benchmark # httperf --num-conns=50 --num-calls=1000 Ruby Version Throughput Latency ------------ ---------- ------- JRuby HEAD 5650 reqs/s (0.2 ms/req) Ruby 1.9.3 5263 reqs/s (0.2 ms/req) JRuby 1.6.7 4303 reqs/s (0.2 ms/req) rbx HEAD 2288 reqs/s (0.4 ms/req)

Slide 161

Slide 161 text

Hello World Comparison Web Server Throughput Latency ---------- ---------- ------- Goliath (0.9.4) 2058 reqs/s (0.5 ms/req) Thin (1.2.11) 7502 reqs/s (0.1 ms/req) Node.js (0.6.5) 11735 reqs/s (0.1 ms/req)

Slide 162

Slide 162 text

0MQ TOO! &HOOXORLG $FWRU &HOOXORLG ,20DLOER[ &HOOXORLG =04 5HDFWRU

Slide 163

Slide 163 text

Celluloid::ZMQ •Built on ffi-rzmq •But exposes a higher level API •Celluloid::IO for ZeroMQ

Slide 164

Slide 164 text

Distributed Celluloid over 0MQ http://github.com/celluloid/reel

Slide 165

Slide 165 text

Mostly ready to use!

Slide 166

Slide 166 text

Probably needs its own talk :(

Slide 167

Slide 167 text

Celluloid-powered Web Framework http://github.com/celluloid/lattice

Slide 168

Slide 168 text

Vaporware!

Slide 169

Slide 169 text

Goals •Reuse parts of Rails •Multithreaded development mode •Easy scatter/gather for SOA

Slide 170

Slide 170 text

That’s all, folks!

Slide 171

Slide 171 text

Bye!

Slide 172

Slide 172 text

Links •http://github.com/celluloid •http://twitter.com/bascule •http://unlimitednovelty.com/