1
# -*- test-case-name: twisted.python.threadable -*-
2
# Copyright (c) 2001-2004 Twisted Matrix Laboratories.
3
# See LICENSE for details.
7
A module that will allow your program to be multi-threaded,
8
micro-threaded, and single-threaded. Currently microthreads are
9
unimplemented. The idea is to abstract away some commonly used
10
functionality so that I don't have to special-case it in all programs.
15
from twisted.python import hook
17
class DummyLock(object):
19
Hack to allow locks to be unpickled on an unthreaded system.
23
return (unpickle_lock, ())
26
if threadingmodule is not None:
30
unpickle_lock.__safe_for_unpickling__ = True
32
def _synchPre(self, *a, **b):
33
if '_threadable_lock' not in self.__dict__:
34
_synchLockCreator.acquire()
35
if '_threadable_lock' not in self.__dict__:
36
self.__dict__['_threadable_lock'] = XLock()
37
_synchLockCreator.release()
38
self._threadable_lock.acquire()
40
def _synchPost(self, *a, **b):
41
self._threadable_lock.release()
43
def synchronize(*klasses):
44
"""Make all methods listed in each class' synchronized attribute synchronized.
46
The synchronized attribute should be a list of strings, consisting of the
47
names of methods that must be synchronized. If we are running in threaded
48
mode these methods will be wrapped with a lock.
50
if threadmodule is not None:
52
for methodName in klass.synchronized:
53
hook.addPre(klass, methodName, _synchPre)
54
hook.addPost(klass, methodName, _synchPost)
56
def init(with_threads=1):
57
"""Initialize threading.
59
Don't bother calling this. If it needs to happen, it will happen.
61
global threaded, _synchLockCreator, XLock
65
if threadmodule is not None:
68
class XLock(threadingmodule._RLock, object):
70
return (unpickle_lock, ())
72
_synchLockCreator = XLock()
74
raise RuntimeError("Cannot initialize threading, platform lacks thread support")
77
raise RuntimeError("Cannot uninitialize threads")
83
if threadmodule is None:
85
return threadmodule.get_ident()
89
"""Are we in the thread responsable for I/O requests (the event loop)?
91
return ioThread == getThreadID()
94
def registerAsIOThread():
95
"""Mark the current thread as responsable for I/O requests.
98
ioThread = getThreadID()
104
def whenThreaded(cb):
105
warnings.warn("threadable.whenThreaded is deprecated. "
106
"Use application-level logic instead.",
107
DeprecationWarning, stacklevel=2)
111
import thread as threadmodule
112
import threading as threadingmodule
115
threadingmodule = None
119
__all__ = ['isInIOThread', 'registerAsIOThread', 'getThreadID', 'XLock',