Created
May 25, 2016 17:09
-
-
Save miyucy/bcf616c519afe5c7ec1108e4c45365e3 to your computer and use it in GitHub Desktop.
Queue Worker
This file contains 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' | |
class QuWk | |
NUM = 3 | |
def initialize | |
@queue = Queue.new | |
@workers = [] | |
@num = NUM | |
@block = proc {} | |
end | |
def close | |
NUM.times { @queue.push nil } | |
@workers.each(&:join) | |
end | |
def push(item) | |
@queue.push item | |
end | |
def register(&block) | |
@block = block | |
end | |
def perform | |
@num.times do |number| | |
worker = Thread.new(@queue, @block) do |queue, block| | |
while item = queue.pop | |
block.call item | |
end | |
end | |
worker[:number] = number | |
@workers.push worker | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment