Last active
August 29, 2015 14:08
-
-
Save ksss/f332b9b11207b4e87ece to your computer and use it in GitHub Desktop.
nano_worker
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
| # NanoWorker | |
| # nano worker implementation use by thread | |
| class NanoWorker | |
| attr_accessor :queue, :thread | |
| @@thread_map = {} | |
| class << self | |
| def [](name) | |
| @@thread_map[name] ||= new | |
| end | |
| def each | |
| @@thread_map.each { |m| yield m } | |
| end | |
| end | |
| def initialize | |
| @queue = Queue.new | |
| @thread = nil | |
| @after_perform = Proc.new{} | |
| end | |
| # set job | |
| # NanoWorker['some_thread_name'].perform(some_obj) do |some_obj_local| | |
| # some_obj_local.some_method | |
| # end | |
| def perform(*args) | |
| @thread ||= Thread.new { | |
| loop do | |
| a = @queue.pop | |
| yield *a | |
| @after_perform.call(self, *a) | |
| end | |
| } | |
| @queue.push args | |
| end | |
| # wait and kill when finish all task | |
| def join | |
| if 0 < @queue.size | |
| after_perform do |m, *other| | |
| m.kill if m.queue.size == 0 | |
| end | |
| @thread.join | |
| end | |
| end | |
| # you can set callback called when after perform | |
| # NanoWorker['some_thread_name'].after_perform do |some_obj_local| | |
| # p some_obj_local | |
| # end | |
| def after_perform(&block) | |
| @after_perform = block | |
| end | |
| def kill | |
| @thread.kill | |
| @queue.clear | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment