Rails源代码研读之ActiveRecord研读

ActiveRecord 的 connection_poll 使用了 Monit
      class Reaper
        attr_reader :pool, :frequency

        def initialize(pool, frequency)
          @pool      = pool
          @frequency = frequency
        end

        def run
          return unless frequency
          Thread.new(frequency, pool) { |t, p|
            while true
              sleep t
              p.reap
            end
          }
        end
      end

      include MonitorMixin

      attr_accessor :automatic_reconnect, :checkout_timeout, :dead_connection_timeout
      attr_reader :spec, :connections, :size, :reaper

      class Latch # :nodoc:
        def initialize
          @mutex = Mutex.new
          @cond  = ConditionVariable.new
        end

        def release
          @mutex.synchronize { @cond.broadcast }
        end

        def await
          @mutex.synchronize { @cond.wait @mutex }
        end
      end



monit是用在多个不同线程同步用的,如下是Ruby的example
require 'monitor.rb'

buf = []
buf.extend(MonitorMixin)
empty_cond = buf.new_cond

# consumer
Thread.start do
  loop do
    buf.synchronize do
      empty_cond.wait_while { buf.empty? }  #Block, 当数据为空
      print buf.shift
    end
  end
end

# producer
while line = ARGF.gets
  buf.synchronize do
    buf.push(line)
    empty_cond.signal  #唤醒另外的一个Thread
  end
end

buf.new_cond   会生成一个 MonitorMixin::ConditionVariable ,
ConditionVariable有很多非常有用的功能

1,  wait_while
def wait_while
  while yield
    wait
  end
end
   
block  线程,等待唤醒

2, signal
Wakes up the first thread in line waiting for this lock.
唤醒第一个Thread为这锁

2, wait_unitl
与1 wait_while 相反



参考处理

Rails中常使用如下的参数形式
def method_a(1,2, :a => 3, :b => 4)

end
一般使用如下形式

def options(*args)
  args.extract_options!
end

options(1, 2)           # => {}
options(1, 2, :a => :b) # => {:a=>:b}

他会将最后的的hash 提取出来。
源代码如下
# File activesupport/lib/active_support/core_ext/array/extract_options.rb, line 22
def extract_options!
  if last.is_a?(Hash) && last.extractable_options?
    pop
  else
    {}
  end
end



你可能感兴趣的:(Rails源代码研读之ActiveRecord研读)