系统编程-进程总结
进程:程序运行在操作系统上的一个实例,就称之为进程。进程需要相应的系统资源:内存、时间片、pid。 创建进程: 首先要导入multiprocessing中的Process: 创建一个Process对象; 创建Process对象时,可以传递参数;
- p = Process(target=XXX,args=(tuple,),kwargs={key:value})
- target = XXX ##指定的任务函数,不用加(),
- args=(tuple,)kwargs={key:value}##给任务函数传递的参数
使用start()启动进程 结束进程 给子进程指定函数传递参数Demo
- import os
- from mulitprocessing import Process
- import time
-
- def pro_func(name,age,**kwargs):
- for i in range(5):
- print("子进程正在运行中,name=%s,age=%d,pid=%d"%(name,age,os.getpid()))
- print(kwargs)
- time.sleep(0.2)
- if __name__ =="__main__":
- #创建Process对象
- p = Process(target=pro_func,args=('小明',18),kwargs={'m':20})
- #启动进程
- p.start()
- time.sleep(1)
- #1秒钟之后,立刻结束子进程
- p.terminate()
- 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:
- from multiprocessing import Process.Queue
- import os,time,random
- #写数据进程执行的代码:
- def write(q):
- for value in ['A','B','C']:
- print("Put %s to queue...",%value)
- q.put(value)
- time.sleep(random.random())
- #读数据进程执行的代码
- def read(q):
- while True:
- if not q.empty():
- value = q.get(True)
- print("Get %s from queue.",%value)
- time.sleep(random.random())
- else:
- break
- if __name__=='__main__':
- #父进程创建Queue,并传给各个子进程
- q = Queue()
- pw = Process(target=write,args=(q,))
- pr = Process(target=read,args=(q,))
- #启动子进程pw ,写入:
- pw.start()
- #等待pw结束
- pw.join()
- #启动子进程pr,读取:
- pr.start()
- pr.join()
- #pr 进程里是死循环,无法等待其结束,只能强行终止:
- print('')
- print('所有数据都写入并且读完')
进程池Pool
- #coding:utf-8
- from multiprocessing import Pool
- import os,time,random
-
- def worker(msg):
- t_start = time.time()
- print("%s 开始执行,进程号为%d"%(msg,os.getpid()))
- # random.random()随机生成0-1之间的浮点数
- time.sleep(random.random()*2)
- t_stop = time.time()
- print(msg,"执行完毕,耗时%0.2f”%(t_stop-t_start))
-
- po = Pool(3)#定义一个进程池,最大进程数3
- for i in range(0,10):
- po.apply_async(worker,(i,))
- print("---start----")
- po.close()
- po.join()
- print("----end----")
进程池中使用Queue
如果要使用Pool创建进程,就需要使用multiprocessing.Manager()中的Queue(),而不是multiprocessing.Queue(),否则会得到如下的错误信息:
RuntimeError: Queue objects should only be shared between processs through inheritance
- from multiprocessing import Manager,Pool
- import os,time,random
- def reader(q):
- print("reader 启动(%s),父进程为(%s)"%(os.getpid(),os.getpid()))
- for i in range(q.qsize()):
- print("reader 从Queue获取到消息:%s"%q.get(True))
-
- def writer(q):
- print("writer 启动(%s),父进程为(%s)"%(os.getpid(),os.getpid()))
- for i ini "itcast":
- q.put(i)
- if __name__ == "__main__":
- print("(%s)start"%os.getpid())
- q = Manager().Queue()#使用Manager中的Queue
- po = Pool()
- po.apply_async(wrtier,(q,))
- time.sleep(1)
- po.apply_async(reader,(q,))
- po.close()
- po.join()
- print("(%s)End"%os.getpid())
免责声明
本站所有资源出自互联网收集整理,本站不参与制作,如果侵犯了您的合法权益,请联系本站我们会及时删除。
本站发布资源来源于互联网,可能存在水印或者引流等信息,请用户自行鉴别,做一个有主见和判断力的用户。
本站资源仅供研究、学习交流之用,若使用商业用途,请购买正版授权,否则产生的一切后果将由下载用户自行承担。