tornado.concurrent — Work with threads and futures

Utilities for working with threads and Futures.

Futures are a pattern for concurrent programming introduced in Python 3.2 in the concurrent.futures package (this package has also been backported to older versions of Python and can be installed with pip install futures). Tornado will use concurrent.futures.Future if it is available; otherwise it will use a compatible class defined in this module.

tornado.concurrent.Future

_DummyFuture 的别名

消费者方法

Future.result(timeout=None)
Future.exception(timeout=None)
Future.add_done_callback(fn)
Future.done()
Future.running()
Future.cancel()
Future.cancelled()

生产者方法

Future.set_result(result)
Future.set_exception(exception)
tornado.concurrent.run_on_executor(fn)[源代码]

Decorator to run a synchronous method asynchronously on an executor.

The decorated method may be called with a callback keyword argument and returns a future.

tornado.concurrent.return_future(f)[源代码]

Decorator to make a function that returns via callback return a Future.

The wrapped function should take a callback keyword argument and invoke it with one argument when it has finished. To signal failure, the function can simply raise an exception (which will be captured by the StackContext and passed along to the Future).

From the caller’s perspective, the callback argument is optional. If one is given, it will be invoked when the function is complete with Future.result() as an argument. If the function fails, the callback will not be run and an exception will be raised into the surrounding StackContext.

If no callback is given, the caller should use the Future to wait for the function to complete (perhaps by yielding it in a gen.engine function, or passing it to IOLoop.add_future).

Usage:

@return_future
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 the same function, provided @return_future appears first. However, consider using @gen.coroutine instead of this combination.

tornado.concurrent.chain_future(a, b)[源代码]

Chain two futures together so that when one completes, so does the other.

The result (success or failure) of a will be copied to b.

內容目录

上一个主题

tornado.autoreload — 自动检测开发中的代码变化

下一个主题

tornado.httputil — HTTP 头 以及 URL 操作

本页