tornado.concurrent — Work with threads and futures¶
Utilities for working with threads and Futures
.
Futures
are a pattern for concurrent programming introduced inPython 3.2 in the concurrent.futures
package. This package definesa mostly-compatible Future
class designed for use from coroutines,as well as some utility functions for interacting with theconcurrent.futures
package.
- class
tornado.concurrent.
Future
[源代码]¶
Placeholder for an asynchronous result.
AFuture
encapsulates the result of an asynchronousoperation. In synchronous applicationsFutures
are usedto wait for the result from a thread or process pool; inTornado they are normally used withIOLoop.add_future
or byyielding them in agen.coroutine
.tornado.concurrent.Future
is similar toconcurrent.futures.Future
, but not thread-safe (and thereforefaster for use with single-threaded event loops).
In addition toexception
andset_exception
, methodsexc_info
andset_exc_info
are supported to capture tracebacks in Python 2.The traceback is automatically available in Python 3, but in thePython 2 futures backport this information is discarded.This functionality was previously available in a separate classTracebackFuture
, which is now a deprecated alias for this class.
在 4.0 版更改:tornado.concurrent.Future
is always a thread-unsafeFuture
with support for theexc_info
methods. Previously it wouldbe an alias for the thread-safeconcurrent.futures.Future
if that package was available and fall back to the thread-unsafeimplementation if it was not.
在 4.1 版更改: If aFuture
contains an error but that error is never observed(by callingresult()
,exception()
, orexc_info()
),a stack trace will be logged when theFuture
is garbage collected.This normally indicates an error in the application, but in caseswhere it results in undesired logging it may be necessary tosuppress the logging by ensuring that the exception is observed:f.add_done_callback(lambda f: f.exception())
.
Consumer methods¶
Future.
result
(timeout=None)[源代码]¶
If the operation succeeded, return its result. If it failed,re-raise its exception.
This method takes atimeout
argument for compatibility withconcurrent.futures.Future
but it is an error to call itbefore theFuture
is done, so thetimeout
is never used.
Future.
exception
(timeout=None)[源代码]¶
If the operation raised an exception, return theException
object. Otherwise returns None.
This method takes atimeout
argument for compatibility withconcurrent.futures.Future
but it is an error to call itbefore theFuture
is done, so thetimeout
is never used.
Future.
excinfo
()[源代码]¶
Returns a tuple in the same format assys.exc_info
or None.
4.0 新版功能.
Future.
add_done_callback
(_fn)[源代码]¶
Attaches the given callback to theFuture
.
It will be invoked with theFuture
as its argument when the Futurehas finished running and its result is available. In Tornadoconsider usingIOLoop.add_future
instead of callingadd_done_callback
directly.
Future.
cancel
()[源代码]¶
Cancel the operation, if possible.
TornadoFutures
do not support cancellation, so this method alwaysreturns False.
Future.
cancelled
()[源代码]¶
Returns True if the operation has been cancelled.
TornadoFutures
do not support cancellation, so this methodalways returns False.
Producer methods¶
Future.
setresult
(_result)[源代码]¶
Sets the result of aFuture
.
It is undefined to call any of theset
methods more than onceon the same object.
Future.
setexc_info
(_exc_info)[源代码]¶
Sets the exception information of aFuture.
Preserves tracebacks on Python 2.
4.0 新版功能.
tornado.concurrent.
runon_executor
(args, *kwargs)[源代码]¶
Decorator to run a synchronous method asynchronously on an executor.
The decorated method may be called with acallback
keywordargument and returns a future.
TheIOLoop
and executor to be used are determined by theio_loop
andexecutor
attributes ofself
. To use different attributes,pass keyword arguments to the decorator:- @run_on_executor(executor='_thread_pool')
def foo(self):
pass
在 4.2 版更改: Added keyword arguments to use alternative attributes.- @run_on_executor(executor='_thread_pool')
tornado.concurrent.
return_future
(_f)[源代码]¶
Decorator to make a function that returns via callback return aFuture
.
The wrapped function should take acallback
keyword argumentand invoke it with one argument when it has finished. To signal failure,the function can simply raise an exception (which will becaptured by theStackContext
and passed along to theFuture
).
From the caller’s perspective, the callback argument is optional.If one is given, it will be invoked when the function is completewithFuture.result()
as an argument. If the function fails, thecallback will not be run and an exception will be raised into thesurroundingStackContext
.
If no callback is given, the caller should use theFuture
towait for the function to complete (perhaps by yielding it in agen.engine
function, or passing it toIOLoop.add_future
).
Usage:- @returnfuture
def future_func(arg1, arg2, callback):
# Do stuff (possibly asynchronous)
callback(result)
@gen.engine
def caller(callback):
yield future_func(arg1, arg2)
callback()
Note that@return_future
and@gen.engine
can be applied to thesame function, provided@return_future
appears first. However,consider using@gen.coroutine
instead of this combination.- @returnfuture
tornado.concurrent.
chain_future
(_a, b)[源代码]¶
Chain two futures together so that when one completes, so does the other.
The result (success or failure) ofa
will be copied tob
, unlessb
has already been completed or cancelled by the timea
finishes.
原文:
https://tornado-zh-cn.readthedocs.io/zh_CN/latest/concurrent.html