From: 7stud -- Date: 2009-09-03T11:49:10+09:00 Subject: Re: Threads - running something in background Alex Zunega wrote: > Hey guys, > > I've been studying Ruby for some weeks now but when it comes to > threads, I know that I am totally unskilled. > > I am trying to build a class which is able to keep updating itself every > X seconds after being initialized. In general terms it would work like > this: > > ---- > class Threading_Test > attr_accessor :i > def initialize > @i = 0 > @j = 0 > neverstop = false > > t1 = Thread.new do > while neverstop == false do > sleep 0.1 #here's the the problem. > @i = @i + 1 > end > end > > t1.run > > puts "I am ready and I keep updating myself. Or not..." > end > end > ---- > > > The problem occurs when I try to add this "sleep 0.1" into the thread > block. The thread only seems to become active when I ask for the @i > value. > I'm not sure what you mean. Try this: class Updater attr_accessor :i def initialize @i = 0 Thread.new do loop do sleep(1) @i += 1 puts "....#{@i}" end end end end upd = Updater.new 5.times do sleep(2) puts upd.i end Here is my output: ....1 1 ....2 ....3 3 ....4 ....5 5 ....6 ....7 7 ....8 ....9 9 -- Posted via http://www.ruby-forum.com/.