lock.rb 483 B

12345678910111213141516171819202122232425
  1. require 'thread'
  2. require 'rack/body_proxy'
  3. module Rack
  4. class Lock
  5. FLAG = 'rack.multithread'.freeze
  6. def initialize(app, mutex = Mutex.new)
  7. @app, @mutex = app, mutex
  8. end
  9. def call(env)
  10. old, env[FLAG] = env[FLAG], false
  11. @mutex.lock
  12. response = @app.call(env)
  13. response[2] = BodyProxy.new(response[2]) { @mutex.unlock }
  14. response
  15. rescue Exception
  16. @mutex.unlock
  17. raise
  18. ensure
  19. env[FLAG] = old
  20. end
  21. end
  22. end