#练习:进程间共享实例 import time,os import random from multiprocessing import Pool,Value,Lock,Manager from multiprocessing.managers import BaseManager class MyManager(BaseManager): pass def Manager(): m=MyManager() m.start() return m class Counter(object): def __init__(self,initval=0): self.val=Value("i",initval) self.lock=Lock() def increment(self): with self.lock: self.val.value+=1 def value(self): with self.lock: return self.val.value MyManager.register("Counter",Counter) def long_time_task(name,counter): time.sleep(0.2) print "run task %s (%s)... " %(name,os.getpid()) start=time.time() for i in range(50): time.sleep(0.01) #进程间共享实例 counter.increment() end=time.time() print "task %s runs %0.2f seconds." %(name,(end-start)) if __name__=="__main__": manager=Manager() counter=manager.Counter(0) print "Parent process %s." % os.getpid() p=Pool(5) for i in range(5): p.apply_async(long_time_task,args=(str(i),counter)) print "Waiting for all subprocesses done..." p.close() p.join() print "All subprocesses done." print counter.value()