Skip to content

Instantly share code, notes, and snippets.

@ileitch
Created June 29, 2013 18:00
Show Gist options
  • Save ileitch/5892066 to your computer and use it in GitHub Desktop.
Save ileitch/5892066 to your computer and use it in GitHub Desktop.
require 'thread'
# in an initializer or something
class WorkerPool
NUM_THREADS = 5
STOP = 0x666
def initialize
@q = Queue.new
@threads = []
end
def start
NUM_THREADS.times do
@threads << Thread.new do
while true do
job, websocket = @q.pop
break if job == STOP
do_work(job, websocket)
end
end
end
end
def stop
NUM_THREADS.times { @q.push(STOP) }
@threads.map(&:join)
end
def enqueue(job, websocket)
@q.push(job, websocket)
end
def do_work(job, websocket)
# .....
notify_complete(websocket)
end
def notify_complete(websocket)
end
end
$wp = WorkerPool.new
$wp.start
at_exit { $wp.stop }
# in your controller
wp.enqueue(job, websocket)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment