python之进程(池)
获得进程id
import os
from multiprocessing import Process
def info(title):
print(title)
print('模块名:',__name__)
print('父进程:',os.getppid())
print("进程号:",os.getpid())
print("\n\n")
def f(name):
info('\033[31;1mfunction f\033[0m')#[yuanlai ]
print('hello',name)
if __name__=='__main__':
info('\033[32;1mmain process line\033[0m')
p=Process(target=f,args=('bob',))
p.start()
p.join()
进程同步
from multiprocessing import Process,Lock
def f(l,i):
l.acquire()
try:
print('hello world',i)
finally:
l.release()
if __name__=='__main__':
lock=Lock()
for num in range(10):
Process(target=f,args=(lock,num)).start()
进程通信
#Queues通信
from multiprocessing import Process,Queue
def f(q):
q.put([42,None,'hello'])
if __name__ == '__main__':
q=Queue()
p=Process(target=f,args=(q,))
p.start()
print(q.get())
p.join()
#Pipes通信
from multiprocessing import Process, Pipe
def f(conn):
conn.send([42,12,'123nxiu'])
conn.close()
if __name__=='__main__':
parent_conn,child__conn=Pipe()
p=Process(target=f,args=(child__conn,))
p.start()
print(parent_conn.recv())
p.join()
进程池
# 进程池内部维护一个进程序列,当使用时,则去进程池中获取一个进程,
# 如果进程池序列中没有可供使用的进进程,那么程序就会等待,
# 直到进程池中有可用进程为止。
#
# 进程池中有两个方法:
# apply同步(串行)
# apply_async异步(并行)
from multiprocessing import Pool,Process,freeze_support
import time,os
def Foo(i):
time.sleep(2)
print("in process",os.getpid())
return i+100
def Bar(arg):
print('-->exec done:',arg,os.getpid())
if __name__=='__main__':#windows上启动多进程,必须以这个开头
freeze_support()
pool=Pool(processes=5)#允许进程池同时放入5个进程,放在进程池里的进程才会运行
print("主进程",os.getpid())
for i in range(10):
pool.apply_async(func=Foo,args=(i,),callback=Bar)#callback回调,执行完Foo之后,主进程再执行回调Bar
#pool.apply(func=Foo,args=(i,))#往进程池中放10个进程
print('end')
pool.close()
pool.join()#进程池中进程执行完毕后再关闭,如果注释,那么程序直接关闭。
Manager
from multiprocessing import Process,Manager
import os
def f(d, l):#字典,列表
d[1] = '1'
d['2'] = 2
d[0.25] = None
l.append (os.getpid())
print(l)
if __name__ == '__main__':
with Manager() as manager:
d=manager.dict()#生成一个字典,可在多个进程间共享和传递
l=manager.list(range(5))#生成一个列表,可在多个进程间共享和传递
p_list=[]
for i in range(10):
p=Process(target=f,args=(d,l))#生成10个进程
p.start()
p_list.append(p)
for res in p_list:#等待结果
res.join()
# if __name__ == '__main__':
# with Manager () as manager:
# d = manager.dict ()
#
# l = manager.list (range (5))
# p_list = []
# for i in range (10):
# p = Process (target=f, args=(d, l))
# p.start ()
# p_list.append (p)
# for res in p_list:
# res.join ()
print(d)
print(l)