Changeset 1025
- Timestamp:
- 01/22/12 08:59:56 (4 months ago)
- Files:
-
- 1 modified
-
hodgestar/PythonCode/Twistify/twistify.py (modified) (4 diffs)
Legend:
- Unmodified
- Added
- Removed
-
hodgestar/PythonCode/Twistify/twistify.py
r1024 r1025 5 5 from functools import partial 6 6 7 from twisted.internet.defer import inlineCallbacks 7 from twisted.internet.defer import inlineCallbacks, DeferredLock 8 8 from twisted.internet.threads import deferToThread 9 9 from twisted.internet import reactor … … 23 23 :param whitelist: 24 24 Names of attributes that don't need to be wrapped. 25 Default: [] 25 26 :type blacklist: list 26 27 :param blacklist: 27 28 Names of attributes that should themselves be 28 29 wrapped by a Twistify object. 30 Default: [] 31 :type synclock: bool 32 :param synclock: 33 If True, only allow one method to execute in a thread 34 at a time (later calls only begin one earlier calls are done). 35 Default: False 29 36 """ 30 37 31 def __init__(self, wrapped, whitelist=(), blacklist=() ):38 def __init__(self, wrapped, whitelist=(), blacklist=(), synclock=False): 32 39 self.__wrapped = wrapped 33 40 self.__whitelist = set(whitelist) 34 41 self.__blacklist = set(blacklist) 42 self.__synclock = None if not synclock else DeferredLock() 35 43 36 44 def __call_in_thread(self, f, *args, **kwargs): 37 return deferToThread(f, *args, **kwargs) 45 if self.__synclock is None: 46 return deferToThread(f, *args, **kwargs) 47 else: 48 49 def call_f(lock): 50 return deferToThread(f, *args, **kwargs) 51 52 def release_lock(result): 53 self.__synclock.release() 54 return result 55 56 locked = self.__synclock.acquire() 57 locked.addCallback(call_f) 58 locked.addBoth(release_lock) 59 return locked 38 60 39 61 def __getattr__(self, name): … … 76 98 print "Test object awake." 77 99 100 print "---" 101 78 102 print "Testing return of a value ..." 79 103 d = proxy.echo("Echo echo echo.") … … 81 105 print "Got back: %r." % (v,) 82 106 107 print "---" 108 109 SyncTestObject = twistify_type(TestObject, synclock=True) 110 synced_proxy = SyncTestObject() 111 112 print "Testing synclock ..." 113 d1 = synced_proxy.sleep(2) 114 d2 = synced_proxy.echo("Echo ...") 115 v = yield d2 116 print "Got back: %r." % (v,) 117 print "Sleep done:", d1.called 118 119 print "---" 120 121 122 def stop_reactor(result): 123 reactor.stop() 124 return result 83 125 84 126 if __name__ == "__main__": 85 main().addBoth( lambda result: reactor.stop())127 main().addBoth(stop_reactor) 86 128 reactor.run()
