The document discusses concurrency and the actor model in Ruby. It describes several Ruby libraries that implement the actor model, including Rubinius Actors, Revactor, and Celluloid. Celluloid code is provided as an example of how to model a barber shop simulation using actors, with Barber and Shop classes that inherit from Celluloid::Actor. Erlang and Elixir code for similar barber shop simulations using the actor model is also shown for comparison. The document notes advantages of the actor model like avoiding shared mutable state and its decentralized nature, but also potential issues like livelocks and deadlocks. It concludes by questioning if better concurrency primitives could be added to Ruby's standard library.
18. class Barber
include Celluloid::Actor
attr_accessor :status
def initialize(shop)
@shop = shop
end
def cut_customer(name)
puts " cutting customer #{name}"
sleep(rand(5)) Text
accident = rand(2)
if accident
puts " finished cutting #{name}"
else
puts " *** whoops, chopped #{name}'s head off ***"
end
shop.customer_leaves!
end
(...)
end
19. class Shop
include Celluloid::Actor
def initialize
@barber = Barber.new(self)
@chairs = []
puts "lights on ..."
end
def waiting_line
@chairs.size
end
def new_customer(name) Text
puts " customer arriving: #{name}"
if waiting_line > 3
puts "*** sorry, #{name}, no room ***"
else
@chairs << name
@barber.cut_customer!(name)
end
end
def customer_leaves
@chairs.shift
end
end
20. shop = Shop.new
['jack', 'john', 'henry', 'tom', 'bob'].each
do |customer|
Text
shop.new_customer!(customer)
end
shop.report
24. %% shop %%
barber_shop() ->
io:format("lights on ... ~n"),
ShopPid = self(),
BarberPid = spawn(fun() -> barber(ShopPid) end),
barber_shop_in_business(BarberPid, []).
barber_shop_in_business(BarberPid, CustomersInChairs) ->
receive
{cut, Customer} ->
% pop customer from list when hair is being cut
remove_customer(BarberPid, CustomersInChairs,
Customer);
barbercheck ->
respond_to_barber(BarberPid, CustomersInChairs);
Customer ->
io:format("~p arrives~n",[Customer]),
% should check the number of customers waiting first
% if all full: customer turned away
add_customer_if_available(BarberPid, CustomersInChairs,
Customer)
end.
25. %% barber %%
barber(ShopPid) ->
ShopPid ! barbercheck,
receive
wakeup ->
barber(ShopPid);
{customer, Customer} ->
cut(ShopPid, Customer),
barber(ShopPid)
end. Text
cut(ShopPid, Name) ->
io:format("cutting ~p~n", [Name]),
% take customer -> can be removed from waiting chairs
ShopPid ! {cut, Name},
timer:sleep(random:uniform(10000)),
io:format("finished cutting: ~p~n", [Name]).
47. !
Speaker Pictures
Sherlock Jr (1924)
@elise_huard Safety Last (1923)
A Woman of Affairs (1928)
Mysteries of a Barbershop (1923)
Translation The Doll (1919)
Intolerance (1926)
Metropolis (1927)
He Who Gets Slapped (1924)
Conference
Laughing Gravy (1931)
Documentation
Ruby Kaigi 2011
http://www.delicious.com/elisehuard/concurrency
Sponsor
Forward