多进程

 

#单进程

#!/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())

 

#定义最大进程数量,Pool默认大小为CPU核心数量

#!/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())

 Win32平台添加如下代码,防止多进程崩溃
 

from multiprocessing import Process, freeze_support

if __name__ == '__main__':
    freeze_support()

 

p.start()来启动子进程

p.join()方法来使得子进程运行结束后再执行父进程

你可能感兴趣的:(多进程)