posted with the help of GPT-4
def square(n):
return n * n
result = map(square, [1, 2, 3, 4, 5])
print(list(result)) # prints: [1, 4, 9, 16, 25]
from multiprocessing import Pool
def square(n):
return n * n
with Pool() as p:
result = p.imap(square, [1, 2, 3, 4, 5])
for num in result:
print(num) # prints: 1, 4, 9, 16, 25 (one at a time, as soon as they are ready)
imap_unordered: This function is similar to imap, but it doesn't guarantee that results will be yielded in the same order that they were put in. This can be more efficient when dealing with tasks of varying lengths, as it allows results from quick tasks to be returned before slow ones.
starmap: This function is similar to imap, but it unpacks each item in the iterable as arguments to the function. This is useful when your function requires multiple arguments.
from multiprocessing import Pool
def multiply(a, b):
return a * b
with Pool() as p:
result = p.starmap(multiply, [(1, 2), (3, 4), (5, 6)])
print(list(result)) # prints: [2, 12, 30]
from multiprocessing import Pool
def square(n):
return n * n
with Pool() as p:
result = p.map_async(square, [1, 2, 3, 4, 5])
print(result.get()) # waits for results and prints: [1, 4, 9, 16, 25]