Skip to content

Instantly share code, notes, and snippets.

@ddrscott
Created February 14, 2013 21:03
Show Gist options
  • Save ddrscott/4956377 to your computer and use it in GitHub Desktop.
Save ddrscott/4956377 to your computer and use it in GitHub Desktop.
A simple last in - first out queue for RubyMotion. I feel like it should be harder than this...
class LifoQueue
def initialize(name, depth)
raise ArgumentError, "depth must be a number greater than zero" unless Fixnum === depth and depth > 0
super
@depth = depth
@stack = []
@mutex = Mutex.new
@queue = Dispatch::Queue.send :new, name
end
def async(&block)
@mutex.synchronize do
if @stack.size >= @depth - 1
@stack.shift
end
patch_state(block, :waiting)
@stack.push(block)
end
call_next
end
def call_next
@queue.async do
next_proc = @mutex.synchronize do
@stack.pop
end
if next_proc
next_proc.state = :calling
next_proc.call
next_proc.state = :done
call_next
end
end
end
def patch_state(obj, initial_state)
obj.instance_variable_set('@_state', initial_state)
def obj.state
@_state
end
def obj.state=(state)
@_state = state
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment