forked from panda3d/panda3d
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paththread.py
More file actions
283 lines (220 loc) · 7.54 KB
/
thread.py
File metadata and controls
283 lines (220 loc) · 7.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
""" This module reimplements Python's native thread module using Panda
threading constructs. It's designed as a drop-in replacement for the
thread module for code that works with Panda; it is necessary because
in some compilation models, Panda's threading constructs are
incompatible with the OS-provided threads used by Python's thread
module. """
__all__ = [
'error', 'LockType',
'start_new_thread',
'interrupt_main',
'exit', 'allocate_lock', 'get_ident',
'stack_size',
'force_yield', 'consider_yield',
'forceYield', 'considerYield',
'TIMEOUT_MAX'
]
from panda3d import core
import sys
if sys.platform == "win32":
TIMEOUT_MAX = float(0xffffffff // 1000)
else:
TIMEOUT_MAX = float(0x7fffffffffffffff // 1000000000)
# These methods are defined in Panda, and are particularly useful if
# you may be running in Panda's SIMPLE_THREADS compilation mode.
force_yield = core.Thread.force_yield
consider_yield = core.Thread.consider_yield
forceYield = force_yield
considerYield = consider_yield
error = RuntimeError
class LockType:
""" Implements a mutex lock. Instead of directly subclassing
PandaModules.Mutex, we reimplement the lock here, to allow us to
provide the described Python lock semantics. In particular, this
allows a different thread to release the lock than the one that
acquired it. """
def __init__(self):
self.__lock = core.Mutex('PythonLock')
self.__cvar = core.ConditionVar(self.__lock)
self.__locked = False
def acquire(self, waitflag = 1, timeout = -1):
self.__lock.acquire()
try:
if self.__locked and not waitflag:
return False
if timeout >= 0:
while self.__locked:
self.__cvar.wait(timeout)
else:
while self.__locked:
self.__cvar.wait()
self.__locked = True
return True
finally:
self.__lock.release()
def release(self):
self.__lock.acquire()
try:
if not self.__locked:
raise error('Releasing unheld lock.')
self.__locked = False
self.__cvar.notify()
finally:
self.__lock.release()
def locked(self):
return self.__locked
__enter__ = acquire
def __exit__(self, t, v, tb):
self.release()
# Helper to generate new thread names
_counter = 0
def _newname(template="Thread-%d"):
global _counter
_counter = _counter + 1
return template % _counter
_threads = {}
_nextThreadId = 0
_threadsLock = core.Mutex('thread._threadsLock')
def start_new_thread(function, args, kwargs = {}, name = None):
def threadFunc(threadId, function = function, args = args, kwargs = kwargs):
try:
try:
function(*args, **kwargs)
except SystemExit:
pass
finally:
_remove_thread_id(threadId)
global _nextThreadId
_threadsLock.acquire()
try:
threadId = _nextThreadId
_nextThreadId += 1
if name is None:
name = 'PythonThread-%s' % (threadId)
thread = core.PythonThread(threadFunc, [threadId], name, name)
thread.setPythonIndex(threadId)
_threads[threadId] = (thread, {}, None)
thread.start(core.TPNormal, False)
return threadId
finally:
_threadsLock.release()
def _add_thread(thread, wrapper):
""" Adds the indicated core.Thread object, with the indicated Python
wrapper, to the thread list. Returns the new thread ID. """
global _nextThreadId
_threadsLock.acquire()
try:
threadId = _nextThreadId
_nextThreadId += 1
thread.setPythonIndex(threadId)
_threads[threadId] = (thread, {}, wrapper)
return threadId
finally:
_threadsLock.release()
def _get_thread_wrapper(thread, wrapperClass):
""" Returns the thread wrapper for the indicated thread. If there
is not one, creates an instance of the indicated wrapperClass
instead. """
threadId = thread.getPythonIndex()
if threadId == -1:
# The thread has never been assigned a threadId. Go assign one.
global _nextThreadId
_threadsLock.acquire()
try:
threadId = _nextThreadId
_nextThreadId += 1
thread.setPythonIndex(threadId)
wrapper = wrapperClass(thread, threadId)
_threads[threadId] = (thread, {}, wrapper)
return wrapper
finally:
_threadsLock.release()
else:
# The thread has been assigned a threadId. Look for the wrapper.
_threadsLock.acquire()
try:
t, locals, wrapper = _threads[threadId]
assert t == thread
if wrapper is None:
wrapper = wrapperClass(thread, threadId)
_threads[threadId] = (thread, locals, wrapper)
return wrapper
finally:
_threadsLock.release()
def _get_thread_locals(thread, i):
""" Returns the locals dictionary for the indicated thread. If
there is not one, creates an empty dictionary. """
threadId = thread.getPythonIndex()
if threadId == -1:
# The thread has never been assigned a threadId. Go assign one.
global _nextThreadId
_threadsLock.acquire()
try:
threadId = _nextThreadId
_nextThreadId += 1
thread.setPythonIndex(threadId)
locals = {}
_threads[threadId] = (thread, locals, None)
return locals.setdefault(i, {})
finally:
_threadsLock.release()
else:
# The thread has been assigned a threadId. Get the locals.
_threadsLock.acquire()
try:
t, locals, wrapper = _threads[threadId]
assert t == thread
return locals.setdefault(i, {})
finally:
_threadsLock.release()
def _remove_thread_id(threadId):
""" Removes the thread with the indicated ID from the thread list. """
# On interpreter shutdown, Python may set module globals to None.
if _threadsLock is None or _threads is None:
return
_threadsLock.acquire()
try:
if threadId in _threads:
thread, locals, wrapper = _threads[threadId]
assert thread.getPythonIndex() == threadId
del _threads[threadId]
thread.setPythonIndex(-1)
finally:
_threadsLock.release()
def interrupt_main():
# TODO.
pass
def exit():
raise SystemExit
def allocate_lock():
return LockType()
def get_ident():
return core.Thread.getCurrentThread().this
def stack_size(size = 0):
raise error
class _local(object):
""" This class provides local thread storage using Panda's
threading system. """
def __del__(self):
i = id(self)
# Delete this key from all threads.
_threadsLock.acquire()
try:
for thread, locals, wrapper in list(_threads.values()):
try:
del locals[i]
except KeyError:
pass
finally:
_threadsLock.release()
def __setattr__(self, key, value):
d = _get_thread_locals(core.Thread.getCurrentThread(), id(self))
d[key] = value
def __getattribute__(self, key):
d = _get_thread_locals(core.Thread.getCurrentThread(), id(self))
if key == '__dict__':
return d
try:
return d[key]
except KeyError:
return object.__getattribute__(self, key)