Code Explanation:
1. Importing ThreadPoolExecutor
from concurrent.futures import ThreadPoolExecutor
This imports ThreadPoolExecutor, which is used to run functions in separate threads for concurrent execution.
It belongs to the concurrent.futures module.
2. Defining the Function
def double(x):
return x * 2
This defines a simple function double() that takes a number x and returns x * 2.
3. Running Tasks Concurrently with ThreadPoolExecutor
with ThreadPoolExecutor(max_workers=2) as executor:
A ThreadPoolExecutor is created with 2 worker threads.
The with statement ensures that the executor is properly shut down after use.
max_workers=2 means up to 2 function calls can run at the same time.
4. Submitting Tasks with executor.map()
results = list(executor.map(double, [1, 2, 3, 4]))
executor.map(double, [1, 2, 3, 4]) will:
Call double(1), double(2), double(3), double(4)
Submit them to the thread pool.
It will run up to 2 at a time (because of max_workers=2).
Returns an iterator of results in the same order as the input list.
list(...) converts the results iterator into a full list.
5. Printing the Result
print(results)
This prints the result of doubling each number from the list [1, 2, 3, 4]:
[2, 4, 6, 8]
Final Output:
[2, 4, 6, 8]
.png)

0 Comments:
Post a Comment