##language:zh [[self:解读_PyTwisted|返回目录]] ''' Twisted中的多任务处理探索 (1) ''' = Twisted中的多任务处理探索 (1) = 如果开发一个服务器的系统,你必然在线程和进程中徘徊选择。因为服务器运行在一个多用户的情况之下,多个用户的请求同时发起,那么我们就要在同一时间为这些用户进行数据处理并将结果返回给用户。你必然要选择将处理分到不同的线程或进程上去做处理,否则用户就只能序列的得到回应,而没有了并发的效果。 先来看看线程,对于twisted,它视不同的情况已经为我们提供了线程使用的框架,这在IReactorThreads接口中已经定义了。但是在IReactorThreads中定义了两种线程的使用方法:'''callFromThread'''和'''callInThread'''。我是用了很久的时间才了解清楚它们的区别及用途。 先来看看callFromThread的一个示例: {{{ #!python from twisted.internet import reactor from twisted.python import threadable threadable.init(1) def notThreadSafe(x): """do something that isn't thread-safe""" # ... def threadSafeScheduler(): """Run in thread-safe manner.""" reactor.callFromThread(notThreadSafe, 3) # will run 'notThreadSafe(3)' # in the event loop }}} 这是Howto中一个比较经典的示例,但是为什么这样用,以及我们在什么场景下来使用callFromThread却实又讲的非常不清晰。我就用了最简单的办法来了解:分析它的代码流。 {{{ #!python from twisted.python import threadable threadable.init(1) }}} 的工作看起来是做了要用的线程表的初始化。它的代码中我们需要关注的代码如下: {{{ #!python _to_be_synched = [] threaded = None ioThread = None threadCallbacks = [] synchronize(_ThreadedWaiter) init(0) }}} 这里,synchronize方法的代码如下: {{{ #!python def synchronize(*klasses): """Make all methods listed in each class' synchronized attribute synchronized. The synchronized attribute should be a list of strings, consisting of the names of methods that must be synchronized. If we are running in threaded mode these methods will be wrapped with a lock. """ global _to_be_synched if not threaded: map(_to_be_synched.append, klasses) return if threaded: import hook for klass in klasses: ## hook.addPre(klass, '__init__', _synch_init) for methodName in klass.synchronized: hook.addPre(klass, methodName, _synchPre) hook.addPost(klass, methodName, _synchPost) }}} 它先通过map(_to_be_synched.append, klasses)来将传入的_ThreadedWaiter加入到_to_be_synched列表中。然后将这个类的所有方法在执行前和执行后都加入同步处理。这里的hook的代码真的是非常有意思,很像aspect(面向方面的编程)中的断言切入。 最后的init(0)所做的就很简单了: {{{ #!python def init(with_threads=1): """Initialize threading. Should be run once, at the beginning of program. """ global threaded, _to_be_synched, Waiter global threadingmodule, threadmodule, XLock, _synchLockCreator if threaded == with_threads: return elif threaded: raise RuntimeError("threads cannot be disabled, once enabled") threaded = with_threads if threaded: log.msg('Enabling Multithreading.') import thread, threading threadmodule = thread threadingmodule = threading Waiter = _ThreadedWaiter XLock = _XLock _synchLockCreator = XLock() synchronize(*_to_be_synched) _to_be_synched = [] for cb in threadCallbacks: cb() else: Waiter = _Waiter # Hack to allow XLocks to be unpickled on an unthreaded system. class DummyXLock: pass XLock = DummyXLock }}} -------------- [[self:解读_PyTwisted|返回目录]]