Rails源代码研读之ActiveRecord研读

2 篇文章 0 订阅
1 篇文章 0 订阅
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



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值