1 # -*- test-case-name: twisted.python.test_threadable -*-
2 # Copyright (c) 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()
95 def registerAsIOThread():
96 """Mark the current thread as responsable for I/O requests.
99 ioThread = getThreadID()
108 import thread as threadmodule
109 import threading as threadingmodule
112 threadingmodule = None
118 __all__ = ['isInIOThread', 'registerAsIOThread', 'getThreadID', 'XLock']