Multiprocessing and concurrent.futures are both libraries in Python used for parallel processing, but they have some differences in their approach and usage.
Multiprocessing is a library that uses multiple processes to run tasks simultaneously. It creates new processes that are separate from the main process and run in parallel. It is a good choice when the tasks to be performed are CPU-bound and can be run independently of each other. Here's an example code snippet:
import multiprocessing
def task(i):
print(f"Task {i} started")
# Do some work here
print(f"Task {i} finished")
if __name__ == "__main__":
p = multiprocessing.Process(target=task, args=(1,))
p.start()
p.join()
In this example, the task function does some work and prints a message when it is started and finished. We create a new process that runs the task function with an argument of 1 using the Process class from the multiprocessing module. We start the process and join it to wait for it to finish before exiting.
Concurrent.futures, on the other hand, is a library that uses threads to achieve parallelism. It allows us to work with threads and submit tasks to be executed in parallel. It is a good choice when the tasks to be performed are I/O-bound and can be performed waiting for input/output. Here's an example code snippet:
import concurrent.futures
def task(i):
print(f"Task {i} started")
# Do some work here
print(f"Task {i} finished")
def main():
with concurrent.futures.ThreadPoolExecutor() as executor:
futures = [executor.submit(task, i) for i in range(5)]
for future in concurrent.futures.as_completed(futures):
print(f"Task {future.args[0]} finished")
if __name__ == "__main__":
main()
In this example, the task function does some