Created
June 29, 2013 18:00
-
-
Save ileitch/5892066 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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