This multiprocessor code works as expected. It creates 4 Python processes and uses them to print numbers from 0 to 39, with a delay after each print. A.
import multiprocessing import time def job(num): print num time.sleep(1) pool = multiprocessing.Pool(4) lst = range(40) for i in lst: pool.apply_async(job, [i]) pool.close() pool.join()
However, when I try to use a multiprocessor package. Lock to prevent multiple processes from printing to standard, the program immediately exits without output.
import multiprocessing import time def job(lock, num): lock.acquire() print num lock.release() time.sleep(1) pool = multiprocessing.Pool(4) l = multiprocessing.Lock() lst = range(40) for i in lst: pool.apply_async(job, [l, i]) pool.close() pool.join()
Why the introduction of a multiprocessor system. Does Lock make this code inoperative?
Update: it works when the lock is declared globally (where I did some fuzzy tests to check if the lock works), unlike the code above, which passes the lock as an argument (in the documentation on Python multiprocessing, the locks are passed as argument). The code below has a ban declared globally, as opposed to passing as an argument in the code above.
import multiprocessing import time l = multiprocessing.Lock() def job(num): l.acquire() print num l.release() time.sleep(1) pool = multiprocessing.Pool(4) lst = range(40) for i in lst: pool.apply_async(job, [i]) pool.close() pool.join()
python multiprocessing
Daniel S.
source share