import multiprocessing import time def func(name): outputline=name for i in range(3): outputline+= " repeat "+str(i) time.sleep(1) return outputline def main(): pool=multiprocessing.Pool(processes=4) result=[] for i in range(4): pname="cpu_%d"%i result.append(pool.apply_async(func, (pname, ))) pool.close() pool.join() for res in result: print res.get() print "all processes done" if __name__ == '__main__': main()
示例2,使用锁同步
import multiprocessing import time def func(name,lock): outputline=name for i in range(3): outputline+= " repeat "+str(i) lock.acquire() print name+" repeat "+str(i) lock.release() time.sleep(1) return outputline def main(): lock=multiprocessing.Lock() subprocesses=[] for i in range(4): pname="cpu_%d"%i process=multiprocessing.Process(target=func, args=(pname,lock)) process.start() subprocesses.append(process) for p in subprocesses: p.join() print "all processes done" if __name__ == '__main__': main()
ref:
http://www.coder4.com/archives/3352
http://www.cnblogs.com/vamei/archive/2012/10/12/2721484.html