Skip to content

Instantly share code, notes, and snippets.

@nat-n
Last active August 29, 2015 14:00
Show Gist options
  • Select an option

  • Save nat-n/59e5b6b003f9e2ec81be to your computer and use it in GitHub Desktop.

Select an option

Save nat-n/59e5b6b003f9e2ec81be to your computer and use it in GitHub Desktop.
A simple Ruby class for managing work queues to be run in series or in parallel.
class WorkQueue
attr_reader :result
def initialize
@q = []
end
def push &block
@q << block
@result= nil
end
def run_series
@result = @q.map { |proc| proc.call }
end
def run_parallel(thread_limit=6, sleep_time=2)
threads = []
@q.each do |proc|
until threads.map { |t| t.status }.count("run") < thread_limit do
sleep sleep_time
end
threads << Thread.new(&proc)
end
@result = threads.map { |t| t.value }
end
def length
@q.length
end
end
# --- # --- # --- # --- # --- # --- # --- # --- # --- # --- # --- # --- # --- #
# Sample Usage #
# --- # --- # --- # --- # --- # --- # --- # --- # --- # --- # --- # --- # --- #
wq = WorkQueue.new
5.times do
wq.push {
# task code
Math::PI
}
end
p wq.run_series
p wq.run_parallel
p wq.result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment