### Navigation
- [index](# "General Index")
- [modules](# "Python Module Index") |
- [next](# "tornado.locks – Synchronization primitives") |
- [previous](# "tornado.gen — Simplify asynchronous code") |
- [Tornado 4.4.dev1 documentation](#) »
- [Coroutines and concurrency](#) »
# `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`](https://docs.python.org/3.4/library/concurrent.futures.html#module-concurrent.futures "(in Python v3.4)") [https://docs.python.org/3.4/library/concurrent.futures.html#module-concurrent.futures] package. This package definesa mostly-compatible [`Future`](# "tornado.concurrent.Future") class designed for use from coroutines,as well as some utility functions for interacting with the[`concurrent.futures`](https://docs.python.org/3.4/library/concurrent.futures.html#module-concurrent.futures "(in Python v3.4)") [https://docs.python.org/3.4/library/concurrent.futures.html#module-concurrent.futures] package.
*class *`tornado.concurrent.``Future`[[source]](#)
Placeholder for an asynchronous result.
A `Future` encapsulates the result of an asynchronousoperation. In synchronous applications `Futures` are usedto wait for the result from a thread or process pool; inTornado they are normally used with [`IOLoop.add_future`](# "tornado.ioloop.IOLoop.add_future") or byyielding them in a [`gen.coroutine`](# "tornado.gen.coroutine").
[`tornado.concurrent.Future`](# "tornado.concurrent.Future") is similar to[`concurrent.futures.Future`](https://docs.python.org/3.4/library/concurrent.futures.html#concurrent.futures.Future "(in Python v3.4)") [https://docs.python.org/3.4/library/concurrent.futures.html#concurrent.futures.Future], but not thread-safe (and thereforefaster for use with single-threaded event loops).
In addition to `exception` and `set_exception`, methods `exc_info`and `set_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 class`TracebackFuture`, which is now a deprecated alias for this class.
Changed in version 4.0: [`tornado.concurrent.Future`](# "tornado.concurrent.Future") is always a thread-unsafe `Future`with support for the `exc_info` methods. Previously it wouldbe an alias for the thread-safe [`concurrent.futures.Future`](https://docs.python.org/3.4/library/concurrent.futures.html#concurrent.futures.Future "(in Python v3.4)") [https://docs.python.org/3.4/library/concurrent.futures.html#concurrent.futures.Future]if that package was available and fall back to the thread-unsafeimplementation if it was not.
Changed in version 4.1: If a [`Future`](# "tornado.concurrent.Future") contains an error but that error is never observed(by calling `result()`, `exception()`, or `exc_info()`),a stack trace will be logged when the [`Future`](# "tornado.concurrent.Future") 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*)[[source]](#)
If the operation succeeded, return its result. If it failed,re-raise its exception.
This method takes a `timeout` argument for compatibility with[`concurrent.futures.Future`](https://docs.python.org/3.4/library/concurrent.futures.html#concurrent.futures.Future "(in Python v3.4)") [https://docs.python.org/3.4/library/concurrent.futures.html#concurrent.futures.Future] but it is an error to call itbefore the [`Future`](# "tornado.concurrent.Future") is done, so the `timeout` is never used.
`Future.``exception`(*timeout=None*)[[source]](#)
If the operation raised an exception, return the [`Exception`](https://docs.python.org/3.4/library/exceptions.html#Exception "(in Python v3.4)") [https://docs.python.org/3.4/library/exceptions.html#Exception]object. Otherwise returns None.
This method takes a `timeout` argument for compatibility with[`concurrent.futures.Future`](https://docs.python.org/3.4/library/concurrent.futures.html#concurrent.futures.Future "(in Python v3.4)") [https://docs.python.org/3.4/library/concurrent.futures.html#concurrent.futures.Future] but it is an error to call itbefore the [`Future`](# "tornado.concurrent.Future") is done, so the `timeout` is never used.
`Future.``exc_info`()[[source]](#)
Returns a tuple in the same format as [`sys.exc_info`](https://docs.python.org/3.4/library/sys.html#sys.exc_info "(in Python v3.4)") [https://docs.python.org/3.4/library/sys.html#sys.exc_info] or None.
New in version 4.0.
`Future.``add_done_callback`(*fn*)[[source]](#)
Attaches the given callback to the [`Future`](# "tornado.concurrent.Future").
It will be invoked with the [`Future`](# "tornado.concurrent.Future") as its argument when the Futurehas finished running and its result is available. In Tornadoconsider using [`IOLoop.add_future`](# "tornado.ioloop.IOLoop.add_future") instead of calling[`add_done_callback`](# "tornado.concurrent.Future.add_done_callback") directly.
`Future.``done`()[[source]](#)
Returns True if the future has finished running.
`Future.``running`()[[source]](#)
Returns True if this operation is currently running.
`Future.``cancel`()[[source]](#)
Cancel the operation, if possible.
Tornado `Futures` do not support cancellation, so this method alwaysreturns False.
`Future.``cancelled`()[[source]](#)
Returns True if the operation has been cancelled.
Tornado `Futures` do not support cancellation, so this methodalways returns False.
### Producer methods
`Future.``set_result`(*result*)[[source]](#)
Sets the result of a `Future`.
It is undefined to call any of the `set` methods more than onceon the same object.
`Future.``set_exception`(*exception*)[[source]](#)
Sets the exception of a `Future.`
`Future.``set_exc_info`(*exc_info*)[[source]](#)
Sets the exception information of a `Future.`
Preserves tracebacks on Python 2.
New in version 4.0.
`tornado.concurrent.``run_on_executor`(**args*, ***kwargs*)[[source]](#)
Decorator to run a synchronous method asynchronously on an executor.
The decorated method may be called with a `callback` keywordargument and returns a future.
The [`IOLoop`](# "tornado.ioloop.IOLoop") and executor to be used are determined by the `io_loop`and `executor` attributes of `self`. To use different attributes,pass keyword arguments to the decorator:
~~~
@run_on_executor(executor='_thread_pool')
def foo(self):
pass
~~~
Changed in version 4.2: Added keyword arguments to use alternative attributes.
`tornado.concurrent.``return_future`(*f*)[[source]](#)
Decorator to make a function that returns via callback return a[`Future`](# "tornado.concurrent.Future").
The wrapped function should take a `callback` 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 the [`StackContext`](# "tornado.stack_context.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 completewith [`Future.result()`](# "tornado.concurrent.Future.result") as an argument. If the function fails, thecallback will not be run and an exception will be raised into thesurrounding [`StackContext`](# "tornado.stack_context.StackContext").
If no callback is given, the caller should use the `Future` towait for the function to complete (perhaps by yielding it in a[`gen.engine`](# "tornado.gen.engine") function, or passing it to [`IOLoop.add_future`](# "tornado.ioloop.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 thesame function, provided `@return_future` appears first. However,consider using `@gen.coroutine` instead of this combination.
`tornado.concurrent.``chain_future`(*a*, *b*)[[source]](#)
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`, unless`b` has already been completed or cancelled by the time `a` finishes.
© Copyright 2009-2016, The Tornado Authors. Created using [Sphinx](http://sphinx-doc.org/) 1.3.5.
- User's guide
- Introduction
- Asynchronous and non-Blocking I/O
- Coroutines
- Queue example - a concurrent web spider
- Structure of a Tornado web application
- Templates and UI
- Authentication and security
- Running and deploying
- Web framework
- tornado.web — RequestHandler and Application classes
- tornado.template — Flexible output generation
- tornado.escape — Escaping and string manipulation
- tornado.locale — Internationalization support
- tornado.websocket — Bidirectional communication to the browser
- HTTP servers and clients
- tornado.httpserver — Non-blocking HTTP server
- tornado.httpclient — Asynchronous HTTP client
- tornado.httputil — Manipulate HTTP headers and URLs
- tornado.http1connection – HTTP/1.x client/server implementation
- Asynchronous networking
- tornado.ioloop — Main event loop
- tornado.iostream — Convenient wrappers for non-blocking sockets
- tornado.netutil — Miscellaneous network utilities
- tornado.tcpclient — IOStream connection factory
- tornado.tcpserver — Basic IOStream-based TCP server
- Coroutines and concurrency
- tornado.gen — Simplify asynchronous code
- tornado.concurrent — Work with threads and futures
- tornado.locks – Synchronization primitives
- tornado.queues – Queues for coroutines
- tornado.process — Utilities for multiple processes
- Integration with other services
- tornado.auth — Third-party login with OpenID and OAuth
- tornado.wsgi — Interoperability with other Python frameworks and servers
- tornado.platform.asyncio — Bridge between asyncio and Tornado
- tornado.platform.caresresolver — Asynchronous DNS Resolver using C-Ares
- tornado.platform.twisted — Bridges between Twisted and Tornado
- Utilities
- tornado.autoreload — Automatically detect code changes in development
- tornado.log — Logging support
- tornado.options — Command-line parsing
- tornado.stack_context — Exception handling across asynchronous callbacks
- tornado.testing — Unit testing support for asynchronous code
- tornado.util — General-purpose utilities
- Frequently Asked Questions
- Release notes
- What's new in Tornado 4.3
- What's new in Tornado 4.2.1
- What's new in Tornado 4.2
- What's new in Tornado 4.1
- What's new in Tornado 4.0.2
- What's new in Tornado 4.0.1
- What's new in Tornado 4.0
- What's new in Tornado 3.2.2
- What's new in Tornado 3.2.1
- What's new in Tornado 3.2
- What's new in Tornado 3.1.1
- What's new in Tornado 3.1
- What's new in Tornado 3.0.2
- What's new in Tornado 3.0.1
- What's new in Tornado 3.0
- What's new in Tornado 2.4.1
- What's new in Tornado 2.4
- What's new in Tornado 2.3
- What's new in Tornado 2.2.1
- What's new in Tornado 2.2
- What's new in Tornado 2.1.1
- What's new in Tornado 2.1
- What's new in Tornado 2.0
- What's new in Tornado 1.2.1
- What's new in Tornado 1.2
- What's new in Tornado 1.1.1
- What's new in Tornado 1.1
- What's new in Tornado 1.0.1
- What's new in Tornado 1.0