首页 > 系统服务 > 详细

多进程

时间:2016-01-15 12:58:04      阅读:179      评论:0      收藏:0      [点我收藏+]

 

#单进程

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!