Here is an example of how to use a Python multiprocessing pool within a loop:
import multiprocessing
def func(x):
return x**2
if __name__ == '__main__':
pool = multiprocessing.Pool(processes=3)
for i in range(10):
result = pool.apply_async(func, [i])
print(result.get())
pool.close()
pool.join()
In this example, we define a function func()
that takes a number x
and returns its square. We then create a multiprocessing pool with three processes using the multiprocessing.Pool()
function.
In the loop, we use the pool's apply_async()
method to submit a new task to the pool for each iteration. The apply_async()
method takes as arguments the function to be executed and the function arguments.
We then call the get()
method on the result
object returned by apply_async()
. The get()
method blocks until the result becomes available from the process.
Finally, we call pool.close()
and pool.join()
to clean up the pool and wait for all processes to complete.
Asked: 2023-02-24 11:00:00 +0000
Seen: 9 times
Last updated: Sep 24 '21