root/tags/release-0.6.2/lib/threads.py

Revision 1, 2.3 kB (checked in by mjoc, 2 years ago)

Initial import.

Line 
1 # OpenDict
2 # Copyright (c) 2003 Martynas Jocius <mjoc@delfi.lt>
3 #
4 # This program is free software; you can redistribute it and/or modify
5 # it under the terms of the GNU General Public License as published by
6 # the Free Software Foundation; either version 2 of the License, or
7 # (at your opinion) any later version.
8 #
9 # This program is distributed in the hope that will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MECHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more detals.
13 #
14 # You shoud have received a copy of the GNU General Public License
15 # along with this program; if not, write to the Free Software
16 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
17 # 02111-1307 USA
18 #
19 # Module: threads
20
21 from threading import *
22 import sys
23 import os
24 import copy
25 import traceback
26 import string
27
28 class KThread(Thread):
29     """Thread that can be killed during its run()"""
30
31     def join(self, timeout=None):
32         """Kill it"""
33
34         Thread.join(self, timeout)
35         print "Thread killing himself"
36         #os._exit(0)
37
38
39 class Process:
40
41     def __init__(self, func, *param):
42         self.__done = 0
43         self.__result = None
44         self.__status = "working"
45
46         self.__C = Condition()
47
48         # Seperate thread
49         self.__T = Thread(target=self.Wrapper, args=(func, param))
50         self.__T.setName("ProcessThread")
51         self.__T.start()
52
53     def __repr__(self):
54         return "<Process at "+hex(id(self))+":"+self.__status+">"
55
56     def __call__(self):
57         self.__C.acquire()
58         while self.__done == 0:
59             self.__C.wait()
60         self.__C.release()
61
62         result = copy.copy(self.__result)
63         return result
64
65     def isDone(self):
66         return self.__done
67
68     def stop(self):
69         # FIXME: this actually doesn't kill the running process
70         # Needs to be done. Help?
71         #Thread.join(self.__T, None)
72         self.__T.join(0)
73
74     def Wrapper(self, func, param):
75         self.__C.acquire()
76         try:
77            self.__result = func(*param)
78         except:
79            self.__result = None
80            print string.join(traceback.format_exception(sys.exc_info()[0], sys.exc_info()[1],
81            sys.exc_info()[2]), "")
82         self.__done = 1
83         self.__status = "self.__result"
84         self.__C.notify()
85         self.__C.release()
86
Note: See TracBrowser for help on using the browser.