I'm breaking my teeth on multiprocessing within Python but I'm not having any luck wrapping my head around the subject. Basically I have a procedure that is time consuming to run. I need to run it for a range of 1 to 100 but I'd like to abort all processes once the condition I'm looking for has been met. The condition being the return value == 90.
Here is a non multiprocess chunk of code. Can anyone give me an example of how they would convert it to a multiprocess function where the the code will exit all process once the condition of "90" has been met?
def Addsomething(i):
SumOfSomething = i + 1
return SumOfSomething
def RunMyProcess():
for i in range(100):
Something = Addsomething(i)
print Something
return
if __name__ == "__main__":
RunMyProcess()
Edit:
I got this error while testing the 3rd version. Any idea what is causing this?
Exception in thread Thread-3:
Traceback (most recent call last):
File "C:\Python27\lib\threading.py", line 554, in __bootstrap_inner
self.run()
File "C:\Python27\lib\threading.py", line 507, in run
self.__target(*self.__args, **self.__kwargs)
File "C:\Python27\lib\multiprocessing\pool.py", line 379, in _handle_results
cache[job]._set(i, obj)
File "C:\Python27\lib\multiprocessing\pool.py", line 527, in _set
self._callback(self._value)
File "N:\PV\_Proposals\2013\ESS - Clear Sky\01-CODE\MultiTest3.py", line 20, in check_result
pool.terminate()
File "C:\Python27\lib\multiprocessing\pool.py", line 423, in terminate
self._terminate()
File "C:\Python27\lib\multiprocessing\util.py", line 200, in __call__
res = self._callback(*self._args, **self._kwargs)
File "C:\Python27\lib\multiprocessing\pool.py", line 476, in _terminate_pool
result_handler.join(1e100)
File "C:\Python27\lib\threading.py", line 657, in join
raise RuntimeError("cannot join current thread")
RuntimeError: cannot join current thread
Maybe something like this is what you're looking for? Keep in mind I'm writing for Python 3. Your print statement above is Python 2, in which case a side note would be to use xrange instead of range.
EDIT:
Here's a somewhat cleaner version that uses the multiprocessing module instead of subprocess:
EDIT 2:
Here's one last version, which I think is much better than the other two: