Executing ThreadPoolExecutor with Context Manager

Another way to instantiate ThreadPoolExecutor to use it as a context manager with the with statement: with ThreadPoolExecutor(max_workers=2) as executor:

In this example, within our main function, we use our ThreadPoolExecutor as a context manager and then call future = executor.submit(message, (message)) twice to process each message in the threadpool.

You can find the following code in the threadPoolConcurrency2.py file in concurrency subfolder:

from concurrent.futures import ThreadPoolExecutordef message(message): print("Processing {}".format(message))def main(): print("Starting ThreadPoolExecutor") with ThreadPoolExecutor(max_workers=2) as executor: future = executor.submit(message, ("message ...

Get Mastering Python for Networking and Security now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.