1、简单多进程
from multiprocessing import Process
import time
def run_proc():
while True:
print("******************** 2 ********************")
time.sleep(1)
def main():
p=Process(target=run_proc)
p.start()
while True:
print("******************** 1 ********************")
time.sleep(1)
if __name__ == "__main__":
main()
2、进程通信
import multiprocessing,time
def A(q):
for i in range(100):
q.put(i)
print("已经放入%d个数:%d"%(q.qsize(),i))
def B(q):
for i in range(100):
time.sleep(1)
q.get(i)
print("还剩下%d个数:%d"%(q.qsize(),i))
def main():
q=multiprocessing.Queue(5)
p1=multiprocessing.Process(target=A,args=(q,))
p2=multiprocessing.Process(target=B,args=(q,))
p1.start()
p2.start()
if __name__ == "__main__":
main()
3、进程池
import multiprocessing,os,time,random
def A(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))
def main():
po=multiprocessing.Pool(3)
for i in range(10):
po.apply_async(A,(i,))
print("----start----")
po.close() # 关闭进程池,关闭后po不再接收新的请求
po.join() # 等待po中所有子进程执行完成,必须放在close语句之后
print("-----end-----")
if __name__ == "__main__":
main()