From: Alex Zunega Date: 2009-09-03T12:43:11+09:00 Subject: Re: Threads - running something in background 7stud -- wrote: > 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. >> > > Also, you should realize that the @i in the class and the @i in the > thread are the same variable. > Therefore, things like this can happen: > > class Updater > attr_accessor :i > > def initialize > @i = 0 > > Thread.new do > loop do > sleep(0.3) > @i += 1 > puts "....#{@i}" > end > end > > end > > end > > > upd = Updater.new > > 3.times do > sleep(2) > puts upd.i > > upd.i = 0 #<-----****** > end > > --output:-- > ....1 > ....2 > ....3 > ....4 > ....5 > ....6 > 6 > ....1 > ....2 > ....3 > ....4 > ....5 > ....6 > ....7 > 7 > ....1 > ....2 > ....3 > ....4 > ....5 > ....6 > 6 Hey 7stud, Thanks for the very prompt answer. I couldn't make myself clear and I'll try harder this time... :) I've just removed two lines from the code you genially sent me. Removing these two lines I got the behavior I would like to have. See the code and results below: >> class Updater >> attr_accessor :i >> ?> def initialize >> @i = 0 >> ?> Thread.new do ?> loop do ?> ?> @i += 1 >> ?> end >> end >> ?> end >> ?> end => nil >> x.i => 213336 >> x.i => 237848 >> I just want something to time these iteration (one per second, for example), and everytime that I insert some "sleep" method, the Updater would "sum 1" to @i only when I try to access @i attribute. What I expect, in other words, is to have an @i very close to the number of seconds of the object life, just to prove that it works... -- Posted via http://www.ruby-forum.com/.