futures (Python 2 Backport of concurrent.futures)

3.4.0 · maintenance · verified Fri Apr 10

The `futures` library is a backport of the `concurrent.futures` module from Python 3, providing a high-level interface for asynchronously executing callables using thread or process pools. It is designed exclusively for Python 2 environments (specifically 2.6 and 2.7), offering a structured way to manage concurrent tasks in older Python runtimes. The current version is 3.4.0, released in October 2022.

Warnings

Install

Imports

Quickstart

Demonstrates basic usage of `ThreadPoolExecutor` to run two simple tasks concurrently and retrieve their results. The `with` statement ensures proper shutdown of the executor. This code is designed for Python 2.

import time
from concurrent.futures import ThreadPoolExecutor

def my_task(name):
    print "Starting task %s" % name # Python 2 print statement
    time.sleep(1) # Simulate work
    print "Finished task %s" % name # Python 2 print statement
    return "Result from %s" % name

if __name__ == '__main__':
    # Create a thread pool with 2 workers
    with ThreadPoolExecutor(max_workers=2) as executor:
        # Submit tasks
        future1 = executor.submit(my_task, "Alpha")
        future2 = executor.submit(my_task, "Beta")

        # Get results (blocks until complete)
        print future1.result()
        print future2.result()

    print "All concurrent tasks completed." # Python 2 print statement

view raw JSON →