Ruby:在成员变量中存储传递的对象

时间:2011-12-08 12:21:43

标签: ruby object pass-by-reference

我是红宝石的新手。为了进入它,我决定实施消费者/生产者范例。执行时我收到以下错误?

/my/path/MyFile.rb:11:in `initialize': undefined local variable or method ` mutex' for    #<Writer:0x7f5f60219de8 @buffer=0> (NameError)
    from /my/path/MyFile.rb:63:in `new'
    from /my/path/MyFile.rb:63

在构造函数中我能够访问互斥对象,但为什么将它分配给成员变量@mutex会导致上述错误?

提前致谢 阿德里安

P.S。这是代码:

require 'thread'

class Writer  
  @buffer
  @mutex
  @numberDeposited
  @running

  def initialize(buffer, mutex, numberDeposited)
    @buffer = buffer
    @mutex = mutex
    @numberDeposited = numberDeposited
    @running = true;
  end

  def write
    while(@running)
      @mutex.synchronize {
        puts "Writer says, \"Doing what I do best... WRITING!\""
        buffer[0] = buffer[0] + 1
      }
      numberDeposited.signal()
      sleep(1)
    end
  end

  def terminate
    @running = false;
  end
end

    class Reader  
      @running
      @buffer
      @mutex
  @numberDeposited

  def initialize(buffer, mutex, numberDeposited)
    @buffer = buffer
    @mutex = mutex
    @numberDeposited = numberDeposited
    @running = true;
  end

  def read()
    while(@running)
      @mutex.synchronize {
        numberDeposited.wait(@mutex)
        puts "Reader says, \"Oh no, Writer that bastard made me work again!­­­ ­­­­­­­­— ­" + buffer[0].to_s() + "­\""
      }
    end
  end

  def terminate
    @running = false;
  end
end

buffer = 0
mutex = Mutex.new
numberDeposited = ConditionVariable.new

writer = Writer.new(buffer, mutex, numberDeposited)
reader = Reader.new(buffer, mutex, numberDeposited)

thread1 = Thread.new{writer.write};
thread2 = Thread.new{reader.read};

thread1.join();
thread2.join();

0 个答案:

没有答案