from multiprocessing import Pool,Lock,Manager import time from functools import partial defworker(lock,x): time.sleep(1)
lock.acquire() try: withopen('result.txt', 'a+') as f: f.writelines(str(x)) finally: lock.release()
if __name__ == '__main__': e1 = time.time() pool = Pool(4) manager = Manager() lock = manager.Lock()
partial_worker = partial(worker, lock) # for i in range(10): # pool.apply_async(partial_worker, (i,)) pool.map(partial_worker, [i for i inrange(10)]) pool.close() pool.join() e2 = time.time() print(float(e2 - e1))
from multiprocessing import Pool import time defmycallback(x): withopen('result.txt', 'a+') as f: f.writelines(str(x)) defworker(num): time.sleep(1) return num if __name__ == '__main__': e1 = time.time() pool = Pool() for i inrange(10): pool.apply_async(worker, (i,), callback=mycallback) pool.close() pool.join() e2 = time.time() print(float(e2 - e1))