【问题标题】:Parent class's instance variable in RubyRuby中父类的实例变量
【发布时间】:2015-02-23 02:45:52
【问题描述】:

因此,无论出于何种原因,ruby 核心 Queue 类中都没有 peek 方法。我正在尝试创建一个实现 peek 方法的子类。但是,我不明白为什么会出现错误。不能以这种方式使用实例变量吗?查看Queue的源码,在父类的构造函数中有实例变量。有没有办法在子类中引用这些?

class PeekQueue < Queue
  def peek
    @mutex.synchronize{
      while true
        if @que.empty?
          raise ThreadError, "queue empty" if non_block
          @waiting.push Thread.current
          @mutex.sleep
        else
          return @que[0]
        end
      end
    }
  end
end

a = PeekQueue.new
a.push(1)
a.peek
NoMethodError: undefined method 'synchronize' for nil:NilClass

编辑:Queue 类是在编译时创建的,这就是为什么我在 github 上的 ruby​​ 源代码上找不到源代码的原因。这是父类的样子: https://gist.github.com/anonymous/574e20fea3a28663bfe2

【问题讨论】:

  • 我不熟悉Queue 类,但你试过queue = Queue.new #=&gt; #&lt;Thread::Queue:0x007fe3e401c898&gt;; enum = queue.to_enum #=&gt; #&lt;Enumerator: #&lt;Thread::Queue:0x007fe3e401c898&gt;:each&gt; 吗? nextpeek 当然会响应枚举数。
  • #<:queue:0x007f85f298d760> 的未定义方法 `each'
  • 你在哪里定义@mutex?这似乎是零
  • 您正在查看的 Queue 的源代码在哪里?在 ruby​​-doc 网站上,我看到了一个似乎没有定义 @mutex 的 C 实现。
  • 如果您使用的是Queueit works 不会出错。但正如@jbeck 所说,这不是 MRI Core Queue class 的样子。

标签: ruby oop


【解决方案1】:

我没有看到那个错误:

irb(main):025:0> qq = PeekQueue.new
=> #<PeekQueue:0x000006002bf498 @que=[], @num_waiting=0, @mutex=#<Mutex:0x000006002bf420>, @cond=#<ConditionVariable:0x000006002bf3f8 @waiters={}, @waiters_mutex=#<Mutex:0x000006002bf3a8>>>
irb(main):026:0> qq.peek
NameError: undefined local variable or method `non_block' for #<PeekQueue:0x000006002bf498>
        from (irb):15:in `block in peek'
        from (irb):12:in `synchronize'
        from (irb):12:in `peek'
        from (irb):26
        from /usr/bin/irb:12:in `<main>'
irb(main):027:0> qq.push 1
=> #<ConditionVariable:0x000006002bf3f8 @waiters={}, @waiters_mutex=#<Mutex:0x000006002bf3a8>>
irb(main):028:0> qq.peek
=> 1

方法#non_block 似乎是个问题。但是对@mutex 的访问适用于您的代码。

【讨论】:

    猜你喜欢
    • 2014-09-21
    • 1970-01-01
    • 2013-03-24
    • 2013-11-26
    • 2015-08-13
    • 2014-10-23
    • 1970-01-01
    • 2021-07-29
    • 1970-01-01
    相关资源
    最近更新 更多