#单进程 #!/usr/bin/python # -*- coding: utf-8 -*- from multiprocessing import Process,Pool import time,os def fs(name,seconds): print ‘%s will sleep: %d s,Now is %s ,fs pid is: %s‘ % (name,seconds,time.ctime(),os.getpid()) time.sleep(seconds) print ‘Now is: %s‘ % (time.ctime()) return ‘fs‘ + name if __name__ == ‘__main__‘: print ‘main Pname is %s‘ % (os.getpid()) for i in range(1,11): p=Process(target=fs,args=(str(i),2)) p.start() p.join() print ‘main end: ‘ + str(os.getpid())
#定义最大进程数量 #!/usr/bin/python # -*- coding: utf-8 -*- from multiprocessing import Process,Pool import time,os def fs(name,seconds): print ‘%s will sleep: %d s,Now is %s ,fs pid is: %s‘ % (name,seconds,time.ctime(),os.getpid()) time.sleep(seconds) print ‘Now is: %s‘ % (time.ctime()) return ‘fs‘ + name if __name__ == ‘__main__‘: print ‘main Pname is %s‘ % (os.getpid()) p=Pool(processes=3) #定义最多开启3个进程 for i in range(1,11): p.apply_async(fs,args=(str(i),2)) p.close() p.join() print ‘main end: ‘ + str(os.getpid())
#获取每个进程的执行结果 from multiprocessing import Process,Pool import time,os def fs(name,seconds): print ‘%s will sleep: %d s,Now is %s ,fs pid is: %s‘ % (name,seconds,time.ctime(),os.getpid()) time.sleep(seconds) print ‘Now is: %s‘ % (time.ctime()) return ‘fs‘ + name if __name__ == ‘__main__‘: print ‘main Pname is %s‘ % (os.getpid()) p=Pool(processes=3) #result只能获取函数fs的return语句的结果,与fs中的print无关 result=[] for i in range(1,11): print ‘i is: %d‘ % (i) result.append(p.apply_async(fs,args=(str(i),2))) p.close() p.join() for r in result: print r.get() print ‘main end: ‘ + str(os.getpid())
原文:http://www.cnblogs.com/dreamer-fish/p/5132917.html