module Sync_m

def sync_lock(m = EX)

def sync_lock(m = EX)
  return unlock if m == UN
  Thread.handle_interrupt(StandardError => :on_blocking) do
    while true
      @sync_mutex.synchronize do
        begin
          if sync_try_lock_sub(m)
            return self
          else
            if sync_sh_locker[Thread.current]
              sync_upgrade_waiting.push [Thread.current, sync_sh_locker[Thread.current]]
              sync_sh_locker.delete(Thread.current)
            else
              unless sync_waiting.include?(Thread.current) || sync_upgrade_waiting.reverse_each.any?{|w| w.first == Thread.current }
                sync_waiting.push Thread.current
              end
            end
            @sync_mutex.sleep
          end
        ensure
          sync_waiting.delete(Thread.current)
        end
      end
    end
  end
  self
end