如何在本地测试并发?

时间:2012-08-14 02:13:26

标签: ruby-on-rails ruby-on-rails-3 concurrency

什么是在本地测试并发性的最佳方法?即我想测试10个并发命中。我知道像Blitz这样的服务。但是,我试图在本地找到一种更简单的方法来测试竞争条件。

有什么想法吗?通过卷曲可能吗?

2 个答案:

答案 0 :(得分:4)

查看Apache Bench(ab)。基本用法很简单:

ab -n 100 -c 10 http://your.application

答案 1 :(得分:0)

对于本地测试测试中的竞争条件,您可以使用这样的帮助

# call block in a forked process
def fork_with_new_connection(config, object = nil, options={})
  raise ArgumentError, "Missing block" unless block_given?
  options = {
     :stop => true, :index => 0
  }.merge(options)

  fork do
    # stop the process after fork
    Signal.trap('STOP') if options[:stop]
    begin
      ActiveRecord::Base.establish_connection(config)
      yield(object)
    ensure
      ActiveRecord::Base.remove_connection
    end
  end
end

# call multiply times blocks
def multi_times_call_in_fork(count=3, &block)
  raise ArgumentError, "Missing block" unless block_given?
  config = ActiveRecord::Base.remove_connection
  pids = []
  count.times do |index|
    pids << fork_with_new_connection(config, nil, :index=>index, &block)
  end

  # continue forked processes
  Process.kill("CONT", *pids)

  Process.waitall
  ActiveRecord::Base.establish_connection(config)
end

# example
multi_times_call_in_fork(5)  do
  # do something with race conditions
  # add asserts 
end