The concurrent.futures.ThreadPoolExecutor class is a built-in class in the concurrent.futures module in Python. It provides a way to asynchronously execute function calls in separate threads within a fixed-size thread pool.

Here is an example of how to use the ThreadPoolExecutor class:

import concurrent.futures

def my_function(param):
    # Perform some computation here
    return result

# Create a ThreadPoolExecutor with 5 worker threads
with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
    # Submit tasks to the executor
    future1 = executor.submit(my_function, param1)
    future2 = executor.submit(my_function, param2)
    
    # Wait for the tasks to complete and get the results
    result1 = future1.result()
    result2 = future2.result()
    
    # Process the results
    print(result1)
    print(result2)

In this example, we create a ThreadPoolExecutor with a maximum of 5 worker threads. We then submit two tasks to the executor using the submit() method, which returns a Future object representing the result of the computation. We can use the result() method of the Future object to retrieve the result once the task is completed.

By using a ThreadPoolExecutor, we can execute multiple tasks concurrently, taking advantage of multiple threads to speed up the execution of our code

python concurrentfuturesThreadPoolExecutor

原文地址: https://www.cveoy.top/t/topic/iRHh 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录