Skip to content

Instantly share code, notes, and snippets.

@trevorwang
Forked from jemminger/async.rb
Created August 18, 2014 05:46
Show Gist options
  • Save trevorwang/5dc1eff58a995bdcdd18 to your computer and use it in GitHub Desktop.
Save trevorwang/5dc1eff58a995bdcdd18 to your computer and use it in GitHub Desktop.
# from http://stackoverflow.com/questions/6499654/is-there-an-asynchronous-logging-library-for-ruby/6527134#6527134
require 'thread'
require 'singleton'
require 'delegate'
require 'monitor'
class Async
include Singleton
def initialize
@queue = Queue.new
Thread.new { loop { @queue.pop.call } }
end
def run(&blk)
@queue.push blk
end
end
class Work < Delegator
include MonitorMixin
def initialize(&work)
super work; @work, @done, @lock = work, false, new_cond
end
def calc
synchronize {
@result, @done = @work.call, true;
@lock.signal
}
end
def __getobj__
synchronize { @lock.wait_while { !@done } }
@result
end
end
Module.class.class_exec {
def async(*method_names)
method_names.each do |method_name|
original_method = instance_method(method_name)
define_method(method_name) do |*args,&blk|
work = Work.new { original_method.bind(self).call(*args,&blk) }
Async.instance.run { work.calc }
return work
end
end
end
}
require 'Logger'
class Logger
async :debug
end
log = Logger.new STDOUT
log.debug "heloo"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment