If you want to do this with threads, a good way is to use Event . Please note that signal.alarm will not work on Windows, so I believe that threads are your best bet, if only in this case.
import threading import time import random class StochasticSearch(object): def __init__(self): self.halt_event = threading.Event() def find_best_result(self, duration): halt_thread = threading.Timer(duration, self.halt_event.set) halt_thread.start() best_result = 0 while not self.halt_event.is_set(): result = self.search() best_result = result if result > best_result else best_result time.sleep(0.5) return best_result def search(self): val = random.randrange(0, 10000) print 'searching for something; found {}'.format(val) return val print StochasticSearch().find_best_result(3)
source share