3 from Queue import Queue
5 def ThreadedMethod(callable, queue):
7 A function decorator that returns a running thread. The thread
8 runs the specified callable and stores the result in the specified
11 def wrapper(args, kwds):
12 class ThreadInstance(threading.Thread):
15 queue.put(callable(*args, **kwds))
19 thread = ThreadInstance()
28 ThreadManager executes a callable in a thread and stores the result
29 in a thread safe queue.
34 def run (self, method, *args, **kwds):
36 Execute a callable in a separate thread.
38 method = ThreadedMethod(method, self.queue)
39 thread = method(args, kwds)
40 self.threads.append(thread)
44 def get_results(self):
46 Return a list of all the results so far. Blocks until
47 all threads are finished.
49 for thread in self.threads:
52 while not self.queue.empty():
53 results.append(self.queue.get())
56 if __name__ == '__main__':
58 def f(name, n, sleep=1):
60 for i in range(n, n+5):
61 print "%s: %s" % (name, i)
66 threads = ThreadManager()
67 threads.run(f, "Thread1", 10, 2)
68 threads.run(f, "Thread2", -10, 1)
70 results = threads.get_results()
71 print "Results:", results