Skip to content

Instantly share code, notes, and snippets.

@JEG2
Created January 25, 2017 15:20
Show Gist options
  • Save JEG2/53b419d709eb0e80412f76c284ff7133 to your computer and use it in GitHub Desktop.
Save JEG2/53b419d709eb0e80412f76c284ff7133 to your computer and use it in GitHub Desktop.
A wannabe GenServer.
class Counter
def initialize(initial_count = 0)
@mailbox = Queue.new
@replies = Queue.new
@state = initial_count
@server = process_messages
end
def increment
mailbox.push([:handle_increment, 1])
end
def read
mailbox.push([:handle_read])
replies.pop
end
private
attr_reader :mailbox, :replies
def process_messages
Thread.new do
loop do
message = mailbox.deq
@state = send(*message)
end
end
end
def handle_increment(amount)
@state + amount
end
def handle_read
replies.push(@state)
@state
end
end
def time_intensive_operation(counter)
sleep(0.005)
counter.increment
end
counter = Counter.new
threads = Array.new(1000) do
Thread.new do
time_intensive_operation(counter)
end
end
threads.each(&:join)
puts counter.read
# ~/Desktop [ruby 2.3.1p112]$ time ruby counter.rb
# 1000
#
# real 0m0.214s
# user 0m0.108s
# sys 0m0.144s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment