码迷,mamicode.com
首页 > 系统相关 > 详细

多进程

时间:2016-01-15 12:59:04      阅读:214      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!