[prev in list] [next in list] [prev in thread] [next in thread] 

List:       ruby-talk
Subject:    Re: a loop in a thread... very greedy
From:       Tiziano Merzi <giuan.m () gmail ! com>
Date:       2007-12-31 8:53:15
Message-ID: 760f85b911d188f7d78edce1c3c1944f () ruby-forum ! com
[Download RAW message or body]

Abraham Tio wrote:
> need a class(we'll call it a 'simulator' since that's what i'm
> attempting to write) to run a loop.
> need that loop to stop when asked to, such as when the user that started
> it clicks a button to stop it.
> 
> i write java that does this sort of thing all the time.
> HOWEVER, when i try it in ruby, only bad things happen.
> 
> check this out:
> 

here a woking code

class Simulator
  attr_accessor :running
  attr_accessor :sim_thread
  def start
    @running = true;    #instance var
    puts "starting simulator..."
    @sim_thread= Thread.new(){  #instance var
      puts "sim thread started"
      while(@running)
        300000.times do |x|
          x+=1
        end
        puts 'did a buncha stuff a simulator might do'
        Thread.pass
      end
      puts "sim thread stopped"
    }
    # @sim_thread.join   no join
    @sim_thread
  end
  def stop
    puts "stopping simulator..."
    @running = false
  end
end
Thread.abort_on_exception = true
simulator = Simulator.new
thread = simulator.start
puts "started simulator, now we stop it.."
simulator.stop
# wait simulator end
simulator.sim_thread.join

Enjoy!
-- 
Posted via http://www.ruby-forum.com/.

[prev in list] [next in list] [prev in thread] [next in thread] 

Configure | About | News | Add a list | Sponsored by KoreLogic