In python 3, you can now open a file safely using the with
clause like this:
with open("stuff.txt") as f:
data = f.read()
Using this method, I don't need to worry about closing the connection
I was wondering if I could do the same for the multiprocessing. For example, my current code looks like:
pool = multiprocessing.Pool(processes=multiprocessing.cpu_count())
pool.starmap(function,list)
pool.close()
pool.join()
Is there any way I could use a with clause to simplify this?
Use Pool. The multiprocessing pool starmap() function will call the target function with multiple arguments. As such it can be used instead of the map() function. This is probably the preferred approach for executing a target function in the multiprocessing pool that takes multiple arguments.
Python multiprocessing Process classAt first, we need to write a function, that will be run by the process. Then, we need to instantiate a process object. If we create a process object, nothing will happen until we tell it to start processing via start() function. Then, the process will run and return its result.
multiprocessing is a package that supports spawning processes using an API similar to the threading module. The multiprocessing package offers both local and remote concurrency, effectively side-stepping the Global Interpreter Lock by using subprocesses instead of threads.
Multiprocessing in Python is a built-in package that allows the system to run multiple processes simultaneously. It will enable the breaking of applications into smaller threads that can run independently.
with multiprocessing.Pool( ... ) as pool:
pool.starmap( ... )
https://docs.python.org/3/library/multiprocessing.html#multiprocessing.pool.Pool
New in version 3.3: Pool objects now support the context management protocol – see Context Manager Types. enter() returns the pool object, and exit() calls terminate().
You can see an example at the bottom of the Pool
section.
Although its more than what the OP asked, if you want something that will work for both Python 2 and Python 3, you can use:
# For python 2/3 compatibility, define pool context manager
# to support the 'with' statement in Python 2
if sys.version_info[0] == 2:
from contextlib import contextmanager
@contextmanager
def multiprocessing_context(*args, **kwargs):
pool = multiprocessing.Pool(*args, **kwargs)
yield pool
pool.terminate()
else:
multiprocessing_context = multiprocessing.Pool
After that, you can use multiprocessing the regular Python 3 way, regardless of which version of Python you are using. For example:
def _function_to_run_for_each(x):
return x.lower()
with multiprocessing_context(processes=3) as pool:
results = pool.map(_function_to_run_for_each, ['Bob', 'Sue', 'Tim']) print(results)
will work in Python 2 or Python 3.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With