Skip to content

Instantly share code, notes, and snippets.

@elisehuard
Created May 28, 2011 14:45
Show Gist options
  • Save elisehuard/996908 to your computer and use it in GitHub Desktop.
Save elisehuard/996908 to your computer and use it in GitHub Desktop.
sleeping barber in elixir
module Barber
def loop(shop_pid)
shop_pid <- 'barbercheck
receive
match 'wakeup
IO.puts "wakeup"
loop(shop_pid)
match {'customer, customer}
cut_hair(shop_pid, customer)
loop(shop_pid)
end
end
def cut_hair(shop_pid, customer)
IO.puts "cutting customer #{customer}"
shop_pid <- {'cut, customer}
IO.puts "customer #{customer} turned into shepherd's pie"
end
end
object Shop
def initialize
shop_pid = Process.current
barber_pid = Process.spawn -> Barber.loop(shop_pid)
@('barber_pid: barber_pid, 'shop_pid: shop_pid)
end
def loop(customers_in_chairs)
IO.puts "shop loop #{customers_in_chairs}"
receive
match {'cut, customer}
if customers_in_chairs.include?(customer)
loop(customers_in_chairs.delete(customer))
else
loop(customers_in_chairs)
end
match 'barbercheck
IO.puts "barber checking ..."
respond_to_barber(customers_in_chairs)
match {'customer, customer}
IO.puts("new customer #{customer}")
add_customer(customers_in_chairs, customer)
match any
IO.puts "matching anything #{any}"
end
end
def add_customer(customers_in_chairs, customer)
if customers_in_chairs.size > 3
loop(customers_in_chairs)
else
@barber_pid <- 'wakeup
loop([customer|customers_in_chairs])
end
end
def respond_to_barber([])
IO.puts "no customers"
loop([])
end
def respond_to_barber([head|tail])
@barber_pid <- {'customer, head}
loop(tail)
end
end
pid = Process.spawn -> Shop.new.loop([])
IO.puts pid
pid <- {'customer, "hello"}
@elisehuard
Copy link
Author

what doesn't work: the 'barbercheck message never seems to arrive to the shop

@elisehuard
Copy link
Author

and it works now, thanks Jose :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment