From: Nathan Date: 2010-04-07T22:52:45+09:00 Subject: Re: modifying a Hash in one process when .each is running in another Thanks for the clarification... My application is network based, and some operations take several seconds. generate_list_of_objects takes anything between 2 and 15 seconds, so I wouldn't like to have my whole program on hold while that's happening. Each test process takes a few seconds too, so if the object is no longer on the list, it isn't a particularly bad thing if test tries to run, but it'll take up a lot of time unnecessarily. I'm trying to work out if there's another way of doing it then. Perhaps I'll modify the test method so that it knows if the current object is on the list, and only runs the test if it is. Nathan On Apr 7, 2:25 pm, Brian Candler wrote: > Nathan Macinnes wrote: > > I want one process to continually loop through a list of objects (in > > the form of a hash), while another process continually refreshes that > > list. I've done it the most obvious way below, but are there any > > pitfalls here? I don't really know how the each method works, so will > > it be looking for keys that may not be there anymore? Would I be > > better off doing some kind of merge of the old hash with the new, > > rather than replacing the old hash entirely? > > Fortunately you are not replacing or modifying the hash at all (and > modifying a hash while iterating through it is a really bad idea) > > Rather, you are updating the local variable 'myHash' to point to a new > hash. The tester thread, once it has started iterating through the old > hash, will continue to do so until it gets to the end. > > You could make this even more explicit by eliminating the 'terminate' > variable: > > tester = Thread.new { >   while myHash >     myHash.each ... >   end > > } > > ... > myHash = nil > tester.join > > But is there a particular reason to do this using threads? It would be > simpler like this: > > while Time.now < time_to_finish >   myHash = MyClass.generate_list_of_objects >   myHash.each do |key,value| >     value.test >   end > end > > Note that MRI won't give you thread concurrency across multiple cores, > although JRuby does. > -- > Posted viahttp://www.ruby-forum.com/.