系统编程-进程总结

本文阅读 4 分钟
首页 Python笔记 正文

进程:程序运行在操作系统上的一个实例,就称之为进程。进程需要相应的系统资源:内存、时间片、pid。 创建进程: 首先要导入multiprocessing中的Process: 创建一个Process对象; 创建Process对象时,可以传递参数;

  1. p = Process(target=XXX,args=(tuple,),kwargs={key:value})
  2. target = XXX ##指定的任务函数,不用加(),
  3. args=(tuple,)kwargs={key:value}##给任务函数传递的参数

使用start()启动进程 结束进程 给子进程指定函数传递参数Demo

  1. import os
  2. from mulitprocessing import Process
  3. import time
  4. def pro_func(name,age,**kwargs):
  5. for i in range(5):
  6. print("子进程正在运行中,name=%s,age=%d,pid=%d"%(name,age,os.getpid()))
  7. print(kwargs)
  8. time.sleep(0.2)
  9. if __name__ =="__main__":
  10. #创建Process对象
  11. p = Process(target=pro_func,args=('小明',18),kwargs={'m':20})
  12. #启动进程
  13. p.start()
  14. time.sleep(1)
  15. #1秒钟之后,立刻结束子进程
  16. p.terminate()
  17. p.join()

注意:进程间不共享全局变量

进程之间的通信-Queue

在初始化Queue()对象时(例如q=Queue(),若在括号中没有指定最大可接受的消息数量,获数量为负值时,那么就代表可接受的消息数量没有上限一直到内存尽头)

Queue.qsize():返回当前队列包含的消息数量

Queue.empty():如果队列为空,返回True,反之False

Queue.full():如果队列满了,返回True,反之False

Queue.get([block[,timeout]]):获取队列中的一条消息,然后将其从队列中移除,

block默认值为True。

如果block使用默认值,且没有设置timeout(单位秒),消息队列如果为空,此时程序将被阻塞(停在读中状态),直到消息队列读到消息为止,如果设置了timeout,则会等待timeout秒,若还没读取到任何消息,则抛出“Queue.Empty"异常:

Queue.get_nowait()相当于Queue.get(False)

Queue.put(item,[block[,timeout]]):将item消息写入队列,block默认值为True; 如果block使用默认值,且没有设置timeout(单位秒),消息队列如果已经没有空间可写入,此时程序将被阻塞(停在写入状态),直到从消息队列腾出空间为止,如果设置了timeout,则会等待timeout秒,若还没空间,则抛出”Queue.Full"异常 如果block值为False,消息队列如果没有空间可写入,则会立刻抛出"Queue.Full"异常; Queue.put_nowait(item):相当Queue.put(item,False)

进程间通信Demo:

  1. from multiprocessing import Process.Queue
  2. import os,time,random
  3. #写数据进程执行的代码:
  4. def write(q):
  5. for value in ['A','B','C']:
  6. print("Put %s to queue...",%value)
  7. q.put(value)
  8. time.sleep(random.random())
  9. #读数据进程执行的代码
  10. def read(q):
  11. while True:
  12. if not q.empty():
  13. value = q.get(True)
  14. print("Get %s from queue.",%value)
  15. time.sleep(random.random())
  16. else:
  17. break
  18. if __name__=='__main__':
  19. #父进程创建Queue,并传给各个子进程
  20. q = Queue()
  21. pw = Process(target=write,args=(q,))
  22. pr = Process(target=read,args=(q,))
  23. #启动子进程pw ,写入:
  24. pw.start()
  25. #等待pw结束
  26. pw.join()
  27. #启动子进程pr,读取:
  28. pr.start()
  29. pr.join()
  30. #pr 进程里是死循环,无法等待其结束,只能强行终止:
  31. print('')
  32. print('所有数据都写入并且读完')

进程池Pool

  1. #coding:utf-8
  2. from multiprocessing import Pool
  3. import os,time,random
  4. def worker(msg):
  5. t_start = time.time()
  6. print("%s 开始执行,进程号为%d"%(msg,os.getpid()))
  7. # random.random()随机生成0-1之间的浮点数
  8. time.sleep(random.random()*2)
  9. t_stop = time.time()
  10. print(msg,"执行完毕,耗时%0.2f”%(t_stop-t_start))
  11. po = Pool(3)#定义一个进程池,最大进程数3
  12. for i in range(0,10):
  13. po.apply_async(worker,(i,))
  14. print("---start----")
  15. po.close()
  16. po.join()
  17. print("----end----")

进程池中使用Queue

如果要使用Pool创建进程,就需要使用multiprocessing.Manager()中的Queue(),而不是multiprocessing.Queue(),否则会得到如下的错误信息:

RuntimeError: Queue objects should only be shared between processs through inheritance

  1. from multiprocessing import Manager,Pool
  2. import os,time,random
  3. def reader(q):
  4. print("reader 启动(%s),父进程为(%s)"%(os.getpid(),os.getpid()))
  5. for i in range(q.qsize()):
  6. print("reader 从Queue获取到消息:%s"%q.get(True))
  7. def writer(q):
  8. print("writer 启动(%s),父进程为(%s)"%(os.getpid(),os.getpid()))
  9. for i ini "itcast":
  10. q.put(i)
  11. if __name__ == "__main__":
  12. print("(%s)start"%os.getpid())
  13. q = Manager().Queue()#使用Manager中的Queue
  14. po = Pool()
  15. po.apply_async(wrtier,(q,))
  16. time.sleep(1)
  17. po.apply_async(reader,(q,))
  18. po.close()
  19. po.join()
  20. print("(%s)End"%os.getpid())
解压密码: detechn或detechn.com

免责声明

本站所有资源出自互联网收集整理,本站不参与制作,如果侵犯了您的合法权益,请联系本站我们会及时删除。

本站发布资源来源于互联网,可能存在水印或者引流等信息,请用户自行鉴别,做一个有主见和判断力的用户。

本站资源仅供研究、学习交流之用,若使用商业用途,请购买正版授权,否则产生的一切后果将由下载用户自行承担。

简述Python里面search和match的区别
« 上一篇 01-31
多进程,多线程,以及协程的理解,项目是否用?
下一篇 » 01-31

发表评论