p=Process(target=info,args=('yuan',)) 第一个参数:进程要执行的函数 第二个参数:函数的参数
is_alive():判断进程是否在运行
run():start()调用run方法,如果实例进程时未传入target,这start执行默认run()方法
进程队列
队列是帮做线程同步用的,为了安全才使用队列
q=multiprocessing.Queue() 进程队列,存在映射关系
q=queue.Queue() 线程队列
数据是拷贝的,进程之间通信非常麻烦,消耗较大
管道
conn 控制权收发消息
parent_conn,child_conn=Pipe() 双向管道
id(child_conn)
进程队列和管道只是完成通信的功能,不能数据共享
Manager():
with Manger() as manager: 不用关闭
变量有自己的id号
通过d=manager.dict() , l=manager.list() 共享数据
进程同步
屏幕本身是共用资源,会造成串行乱套
with l 不用release,acquire,写锁名就可以
=》l.acquire() l.release()
进程之间内存空间相互独立,数据是没有任何关系,但也有共享的资源
import queue,time import multiprocessing def foo(q,s): time.sleep(1) print("son process",id(q)) q.put(123) q.put(s) q.put("yuan") def fot(q,s): time.sleep(3) data=q.get() print('----',data) print("son process",id(q)) q.put(123) q.put(s) q.put("yuan") if __name__ == '__main__': #q=queue.Queue() q=multiprocessing.Queue() p1=multiprocessing.Process(target=foo,args=(q,1)) p2=multiprocessing.Process(target=fot,args=(q,2)) p1.start() p2.start() p1.join() p2.join() print("main process",id(q)) print(q.get()) print(q.get()) print(q.get()) print(q.get()) print(q.get()) # from multiprocessing import Process, Pipe # def f(conn): # conn.send([12, {"name":"yuan"}, 'hello']) # response=conn.recv() # print("response",response) # conn.close() # print("q_ID2:",id(conn)) # # if __name__ == '__main__': # # parent_conn, child_conn = Pipe() #双向管道 # # print("q_ID1:",id(child_conn)) # p = Process(target=f, args=(child_conn,)) # p.start() # # print(parent_conn.recv()) # prints "[42, None, 'hello']" # parent_conn.send("儿子你好!") # p.join() # # # from multiprocessing import Process, Manager # # def f(d, l,n): # # d[n] = '1' #{0:"1"} # d['2'] = 2 #{0:"1","2":2} # # l.append(n) #[0,1,2,3,4, 0,1,2,3,4,5,6,7,8,9] # #print(l) # # # if __name__ == '__main__': # # with Manager() as manager: # # d = manager.dict()#{} # # l = manager.list(range(5))#[0,1,2,3,4] # # # p_list = [] # # for i in range(10): # p = Process(target=f, args=(d,l,i)) # p.start() # p_list.append(p) # # for res in p_list: # res.join() # # print(d) # print(l)
from multiprocessing import Process, Lock import time def f(l, i): l.acquire() time.sleep(1) print('hello world %s' % i) l.release() if __name__ == '__main__': lock = Lock() for num in range(10): Process(target=f, args=(lock, num)).start()