上QQ阅读APP看书,第一时间看更新
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 ThreadPoolExecutor
def message(message):
print("Processing {}".format(message))
def main():
print("Starting ThreadPoolExecutor")
with ThreadPoolExecutor(max_workers=2) as executor:
future = executor.submit(message, ("message 1"))
future = executor.submit(message, ("message 2"))
print("All messages complete")
if __name__ == '__main__':
main()