From: Robert Klemme Date: 2007-06-08T19:25:03+09:00 Subject: Re: What about a 'series' type? On 07.06.2007 23:12, Robert Dober wrote: > On 6/7/07, Robert Klemme wrote: >> On 07.06.2007 21:41, Robert Dober wrote: >> > On 6/7/07, Robert Klemme wrote: >> > >> > Robert I hope you do not mind my fantasy about/over/at??? your theme. >> >> Not at all. I had thought about the limit myself but did not want to >> bother implementing it. Two remarks about your code: >> >> You include Enumerable but do not provide #each which is required. > Sure, bad error; that was a leftover of your code, I do not really > want to include it. >> >> You use instance variables for the iteration which is a bad thing >> because this needless restricts usability (namely in the light of >> multiple threads). > I am not sure I understand this point, but we can get rid of that by > expanding compute_next, but this will make the code much less readable > :( You can as well add parameters and return values to compute_next. > The whole beast is not thread safe at all I guess, even without the > instance var. Oh, it's perfectly thread safe if you change the use of instance variables. > It would be a nice challenge to make it thread safe, I guess we would > need to cache values and synchronize the computation part, sounds > *very* expansive, time and memory wise; probably not worth it . Caching is only needed if you want to make it faster or more efficient. But for a general implementation I would not do it as it can have all sorts of unwanted side effects. >> Array and other's also do not store the iteration >> state in instance variables but in local variables in method #each. > Would that not be for performance reasons? That's another advantage. >> You >> can try it with something like this which would not work if instance >> variables would be used for storing iteration state >> >> a=(1..10).to_a >> 2.times {|i| Thread.new(i) {|j| a.each {|x| puts "[#{j}-#{x}]"; sleep >> 0.5}}} > I guess I do not know enough to understand this :( > How is concurrent access to the method not a problem with local variables? Because then there is iteration state per method invocation. Compare these two variants of #each: class Foo # a must be an Array def initialize(a) @a=a.dup end # thread safe def each_1 for i in 0...@a.size yield @a[i] end self end # not thread safe def each_2 for @i in 0...@a.size yield @a[@i] end self end end Now, think about what happens if two threads invoke #each_1 and #each_2. > However it would be sufficient to synchronize the access to the method > only and not the access to the ivar. That would work but it would limit usability - and there is no need to do that. Kind regards robert