From: Robert Klemme Date: 2008-08-23T02:11:07+09:00 Subject: Re: Saving the state of a Thread? On 22.08.2008 18:11, Patrick Li wrote: > So if I know the status of a thread, (ie. status = 2), and I know the > values of the local variables. > Is there way I can "jump" to that line in the method? I would not speak of the status of a thread. Instead I would model this as status of calculation using command pattern with multiple operation classes. Rough idea: break down the computation into multiple stages. Each stage is handled by an instance of a single class. Every stage knows its successor stages. When a stage is completed a central coordinator saves the next state processor (or just the class) along with its input via Marshalling into a file. Something along the lines of #!/bin/env ruby require 'fileutils' class Coordinator def initialize state_file, processor = nil @state_file = state_file if File.readable? state_file @current_processor = load else @current_processor = processor save processor end end def run loop do next_stage = @current_processor.call if next_stage save next_stage @current_processor = next_stage else # done, return last processor with result clear return @current_processor end end end private def save st printf "saving %p\n", st File.open(@state_file + ".tmp", "wb") {|io| Marshal.dump(st,io)} FileUtils.mv @state_file + ".tmp", @state_file end def load File.open(@state_file, "rb") {|io| Marshal.load(io)} end def clear FileUtils.rm_f @state_file end end # simple exsample Processor = Struct.new :start, :last, :sum do def call limit = [start + 100, last].min self.sum ||= 0 for i in start .. limit self.sum += i end return nil if limit == last res = self.class.new res.sum = self.sum res.start = limit res.last = self.last res end end # run pr = Processor.new 1, 1_000_000, 0 c = Coordinator.new "x.bin", pr puts c.run.sum Of course I could have created two processor types, one for the initial phase (i.e. where start + 10 < end) and one for the last chunk - but I was lazy. At least the program works - you can break it at any step and it will resume processing. Kind regards robert