Advertisement
Guest User

ensure called on StackOverFlow ?

a guest
Aug 16th, 2018
118
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Ruby 2.01 KB | None | 0 0
  1.  
  2. require 'concurrent'
  3. require 'monitor'
  4. require 'singleton'
  5. require 'thread'
  6.  
  7. class Logger
  8.   include Singleton
  9.   def initialize()
  10.     @queue = Queue.new
  11.     Thread.new {
  12.       loop do
  13.         while msg = @queue.shift
  14.           $stderr.puts msg
  15.         end
  16.       end
  17.     }
  18.   end
  19.  
  20.   def write(msg)
  21.     @queue << msg
  22.   end
  23. end
  24.  
  25. LOGGER = Logger.instance
  26.  
  27. class OverflowedLockTester
  28.   include MonitorMixin
  29.  
  30.   def initialize(*args)
  31.     super(*args)
  32.   end
  33.  
  34.   def log_count(what)
  35.     name = @mon_owner.name rescue 'none'
  36.     log format("Current Owner: [%s] - Current Count: [%d] (%s)", name, @mon_count, what.to_s)
  37.   end
  38.  
  39.   def log(mesg)
  40.     LOGGER.write format("%s - %s (#%d): %s",
  41.       Time.now.strftime('%Y-%m-%d %H:%M:%S.%6N'),
  42.       Thread.current.name, Thread.current.object_id, mesg)
  43.   end
  44.  
  45.   def overflow_now
  46.     overflow_now
  47.   end
  48.  
  49.   def run(overflow, event)
  50.     # event is our barrier. If we're not in overflow mode, then we wait
  51.     # until the overflow thread is in synchronize (see below) to allow
  52.     # the other threads to continue
  53.     event.wait unless overflow
  54.     log_count(:checking)
  55.  
  56.     synchronize do
  57.       log_count(:taken)
  58.  
  59.       unless event.set?
  60.         event.set # release the other threads
  61.       end
  62.  
  63.       if overflow
  64.         log_count(:overflowing)
  65.         overflow_now
  66.       end
  67.  
  68.       log_count(:releasing)
  69.     end
  70.     log_count(:released)
  71.   ensure
  72.     log_count(:ensure_called)
  73.   end
  74. end
  75.  
  76. event       = Concurrent::Event.new
  77. lock_tester = OverflowedLockTester.new
  78. threads     = []
  79.  
  80. threads << Thread.new do
  81.  
  82.   Thread.current.name = 'thread-0'
  83.   loop {
  84.     begin
  85.       lock_tester.run(true, event)
  86.     rescue
  87.       LOGGER.write "Failed due to: #{$!.class.name}: #{$!.message}\n\t#{$!.backtrace.join("\n\t")}"
  88.     end
  89.     sleep 1
  90.   }
  91. end
  92.  
  93. 1.upto(1) do |i|
  94.   threads << Thread.new {
  95.     Thread.current.name = "thread-#{i}"
  96.     lock_tester.run(false, event)
  97.     LOGGER.write "#{Thread.current.name}: done"
  98.   }
  99. end
  100.  
  101. threads.map(&:join)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement