sfa-0.9-17 tag
[sfa.git] / sfa / util / threadmanager.py
1 import threading
2 import time
3 from Queue import Queue
4
5 def ThreadedMethod(callable, queue):
6     """
7     A function decorator that returns a running thread. The thread
8     runs the specified callable and stores the result in the specified
9     results queue
10     """
11     def wrapper(args, kwds):
12         class ThreadInstance(threading.Thread): 
13             def run(self):
14                 try:
15                     queue.put(callable(*args, **kwds))
16                 except:
17                     # ignore errors
18                     pass
19         thread = ThreadInstance()
20         thread.start()
21         return thread
22     return wrapper
23
24  
25
26 class ThreadManager:
27     """
28     ThreadManager executes a callable in a thread and stores the result
29     in a thread safe queue. 
30     """
31     queue = Queue()
32     threads = []
33
34     def run (self, method, *args, **kwds):
35         """
36         Execute a callable in a separate thread.    
37         """
38         method = ThreadedMethod(method, self.queue)
39         thread = method(args, kwds)
40         self.threads.append(thread)
41
42     start = run
43
44     def get_results(self):
45         """
46         Return a list of all the results so far. Blocks until 
47         all threads are finished. 
48         """
49         for thread in self.threads:
50             thread.join()
51         results = []
52         while not self.queue.empty():
53             results.append(self.queue.get())  
54         return results
55            
56 if __name__ == '__main__':
57
58     def f(name, n, sleep=1):
59         nums = []
60         for i in range(n, n+5):
61             print "%s: %s" % (name, i)
62             nums.append(i)
63             time.sleep(sleep)
64         return nums
65
66     threads = ThreadManager()
67     threads.run(f, "Thread1", 10, 2)
68     threads.run(f, "Thread2", -10, 1)
69
70     results = threads.get_results()
71     print "Results:", results