OLD | NEW |
| (Empty) |
1 # Copyright (c) 2001-2007 Twisted Matrix Laboratories. | |
2 # See LICENSE for details. | |
3 | |
4 """ | |
5 Extended thread dispatching support. | |
6 | |
7 For basic support see reactor threading API docs. | |
8 | |
9 Maintainer: U{Itamar Shtull-Trauring<mailto:twisted@itamarst.org>} | |
10 """ | |
11 | |
12 import Queue | |
13 | |
14 from twisted.python import failure | |
15 from twisted.internet import defer | |
16 | |
17 | |
18 def _putResultInDeferred(deferred, f, args, kwargs): | |
19 """ | |
20 Run a function and give results to a Deferred. | |
21 """ | |
22 from twisted.internet import reactor | |
23 try: | |
24 result = f(*args, **kwargs) | |
25 except: | |
26 f = failure.Failure() | |
27 reactor.callFromThread(deferred.errback, f) | |
28 else: | |
29 reactor.callFromThread(deferred.callback, result) | |
30 | |
31 | |
32 def deferToThread(f, *args, **kwargs): | |
33 """ | |
34 Run function in thread and return result as Deferred. | |
35 """ | |
36 d = defer.Deferred() | |
37 from twisted.internet import reactor | |
38 reactor.callInThread(_putResultInDeferred, d, f, args, kwargs) | |
39 return d | |
40 | |
41 | |
42 def _runMultiple(tupleList): | |
43 """ | |
44 Run a list of functions. | |
45 """ | |
46 for f, args, kwargs in tupleList: | |
47 f(*args, **kwargs) | |
48 | |
49 | |
50 def callMultipleInThread(tupleList): | |
51 """ | |
52 Run a list of functions in the same thread. | |
53 | |
54 tupleList should be a list of (function, argsList, kwargsDict) tuples. | |
55 """ | |
56 from twisted.internet import reactor | |
57 reactor.callInThread(_runMultiple, tupleList) | |
58 | |
59 | |
60 def blockingCallFromThread(reactor, f, *a, **kw): | |
61 """ | |
62 Run a function in the reactor from a thread, and wait for the result | |
63 synchronously, i.e. until the callback chain returned by the function | |
64 get a result. | |
65 | |
66 @param reactor: The L{IReactorThreads} provider which will be used to | |
67 schedule the function call. | |
68 @param f: the callable to run in the reactor thread | |
69 @type f: any callable. | |
70 @param a: the arguments to pass to C{f}. | |
71 @param kw: the keyword arguments to pass to C{f}. | |
72 | |
73 @return: the result of the callback chain. | |
74 @raise: any error raised during the callback chain. | |
75 """ | |
76 queue = Queue.Queue() | |
77 def _callFromThread(): | |
78 result = defer.maybeDeferred(f, *a, **kw) | |
79 result.addBoth(queue.put) | |
80 reactor.callFromThread(_callFromThread) | |
81 result = queue.get() | |
82 if isinstance(result, failure.Failure): | |
83 result.raiseException() | |
84 return result | |
85 | |
86 | |
87 __all__ = ["deferToThread", "callMultipleInThread", "blockingCallFromThread"] | |
88 | |
OLD | NEW |