八.多线程与多进程
進程與線程的區(qū)別
線程共享內(nèi)存空間,進程的內(nèi)存是獨立的。
線程可以直接訪問進程里數(shù)據(jù)的片段,多個子進程的數(shù)據(jù)是相互獨立的。
同一個進程的線程直接可以交流,兩個進程想通信必須通過一個中間代理來實現(xiàn)。
創(chuàng)建新線程很簡單,創(chuàng)建新進程需要對其父進程進行一次克隆
一個線程可以控制和操作同一進程里的其他線程,進程只能操作子進程。
對于主線程修改,有可能影響其他線程的運行。對父進程修改不會影響其他子進程。
?
#多線程示例 import threading def run(n):print("task",n)t1=threading.Thread(target=run,args=("t1",)) t2=threading.Thread(target=run,args=("t2",))t1.start() t2.start()?
?
?
?
queue隊列
作用:
1.解耦,使程序之間實現(xiàn)松耦合,修改模塊不會影響其他模塊
2.提高處理效率
queue與list區(qū)別:
queue拿取數(shù)據(jù),數(shù)據(jù)取走就沒了,list拿取數(shù)據(jù),數(shù)據(jù)還在list。
q=queue.Queue()#先入先出 q.put()#放數(shù)據(jù) q.get()#取數(shù)據(jù) q.queue.LifoQueue()#后進先出?
import queue q=queue.PriorityQueue()#存儲數(shù)據(jù)時可以設置優(yōu)先級 q.put((2,"b")) q.put((3,"c")) q.put((1,"a"))#輸出結果 (1, 'a') (2, 'b') (3, 'c') #生產(chǎn)者消費者模型 import queueimport threading
import time
q=queue.Queue()
def Producer(name):
count = 1
while True:
q.put("商品%s" % count)
print("%s生產(chǎn)了商品"%name,count)
count += 1
time.sleep(0.5)
def Consumer(name):
while True:
print("%s買到商品%s" %(name, q.get()))
time.sleep(1)
p=threading.Thread(target=Producer,args=("生產(chǎn)者",))
c1=threading.Thread(target=Consumer,args=("買家1",))
c2=threading.Thread(target=Consumer,args=("買家2",))
p.start()
c1.start()
c2.start()
?
?
多進程
import multiprocessing import timedef run(name):time.sleep(2)print('hello',name)if __name__ == '__main__': for i in range(10): p = multiprocessing.Process(target=run,args=('man %s'%i,)) p.start()?
進程間通訊
Queue
from multiprocessing import Process,Queue import threadingdef f(q):q.put([123,'abc'])if __name__ == '__main__':q = Queue() p = Process(target=f, args=(q,)) p.start() print(q.get())?
Pipe
from multiprocessing import Process,Pipedef a(message):message.send([123,"fghr"])message.closeif __name__ == "__main__":pointa,pointb=Pipe()p=Process(target=a,args=(pointa,)) p.start() print(pointb.recv())?
manage
以代理的方式在進程間共享字典或列表形式的數(shù)據(jù)
from multiprocessing import Process, Manager import os def f(d, l):d[os.getpid()] =os.getpid()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)) p.start() p_list.append(p) for res in p_list: #等待結果 res.join() print(d) print(l)?
進程池
進程池內(nèi)部維護一個進程序列,當使用時,則去進程池中獲取一個進程,如果進程池序列中沒有可供使用的進進程,那么程序就會等待,直到進程池中有可用進程為止。
from multiprocessing import Process, Pool import time import osdef 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__': pool = Pool(processes=3) #允許進程池同時放入5個進程 print("主進程",os.getpid()) for i in range(10): pool.apply_async(func=Foo, args=(i,), callback=Bar) #callback=回調(diào) #pool.apply(func=Foo, args=(i,)) #串行 #pool.apply_async(func=Foo, args=(i,)) #并行 print('end') pool.close()#這里join一定是在close之后,且必須要加join,否則主進程不等待創(chuàng)建的子進程執(zhí)行完畢 pool.join() #進程池中進程執(zhí)行完畢后再關閉,如果注釋,那么程序直接關閉。.join()?
轉(zhuǎn)載于:https://www.cnblogs.com/hiss/p/8455884.html
總結
- 上一篇: 突出告警信息(DBA_OUTSTANDI
- 下一篇: django用户认证系统——注册3