Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- require 'concurrent'
- require 'monitor'
- require 'singleton'
- require 'thread'
- class Logger
- include Singleton
- def initialize()
- @queue = Queue.new
- Thread.new {
- loop do
- while msg = @queue.shift
- $stderr.puts msg
- end
- end
- }
- end
- def write(msg)
- @queue << msg
- end
- end
- LOGGER = Logger.instance
- class OverflowedLockTester
- include MonitorMixin
- def initialize(*args)
- super(*args)
- end
- def log_count(what)
- name = @mon_owner.name rescue 'none'
- log format("Current Owner: [%s] - Current Count: [%d] (%s)", name, @mon_count, what.to_s)
- end
- def log(mesg)
- LOGGER.write format("%s - %s (#%d): %s",
- Time.now.strftime('%Y-%m-%d %H:%M:%S.%6N'),
- Thread.current.name, Thread.current.object_id, mesg)
- end
- def overflow_now
- overflow_now
- end
- def run(overflow, event)
- # event is our barrier. If we're not in overflow mode, then we wait
- # until the overflow thread is in synchronize (see below) to allow
- # the other threads to continue
- event.wait unless overflow
- log_count(:checking)
- synchronize do
- log_count(:taken)
- unless event.set?
- event.set # release the other threads
- end
- if overflow
- log_count(:overflowing)
- overflow_now
- end
- log_count(:releasing)
- end
- log_count(:released)
- ensure
- log_count(:ensure_called)
- end
- end
- event = Concurrent::Event.new
- lock_tester = OverflowedLockTester.new
- threads = []
- threads << Thread.new do
- Thread.current.name = 'thread-0'
- loop {
- begin
- lock_tester.run(true, event)
- rescue
- LOGGER.write "Failed due to: #{$!.class.name}: #{$!.message}\n\t#{$!.backtrace.join("\n\t")}"
- end
- sleep 1
- }
- end
- 1.upto(1) do |i|
- threads << Thread.new {
- Thread.current.name = "thread-#{i}"
- lock_tester.run(false, event)
- LOGGER.write "#{Thread.current.name}: done"
- }
- end
- threads.map(&:join)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement