當(dāng)前位置:
首頁(yè) >
进程浅析
發(fā)布時(shí)間:2025/5/22
35
豆豆
1 from multiprocessing import Pipe,Process
2
3 def fun(conn):
4 conn.send([12,{'hello':'c'},'python'])
5 data=conn.recv()
6 conn.close()
7 print(id(conn),data)
8
9
10 if __name__=='__main__':
11
12 parent_conn,child_conn=Pipe() #獲取一個(gè)管道對(duì)象
13 p=Process(target=fun,args=(child_conn,)) #創(chuàng)建一個(gè)進(jìn)程對(duì)象 導(dǎo)包也得是大寫(xiě)
14 p.start()
15
16 print(parent_conn.recv(),id(parent_conn))
17 parent_conn.send('兒子你好')
18 p.join()
?>>>>>>>>>>>>>>>>>>>>>>>>>>>>管道對(duì)象處理進(jìn)程數(shù)據(jù)的收發(fā)
1 import multiprocessing 2 def show(num,l): 3 # with l: #如果用with則默認(rèn)寫(xiě)鎖名就上鎖 4 l.acquire() #啟動(dòng)鎖 5 print('hello python process %s'%num) 6 l.release() #釋放鎖 7 8 if __name__=='__main__': 9 lock=multiprocessing.Lock() #創(chuàng)建一個(gè)進(jìn)程同步鎖 10 for i in range(10): 11 p=multiprocessing.Process(target=show,args=(i,lock)).start() #生成并啟動(dòng)十個(gè)進(jìn)程對(duì)象>>>>>>>>>>>>>>>>>同步鎖實(shí)現(xiàn)進(jìn)程的同步? 為了避免同一時(shí)刻爭(zhēng)搶資源造成數(shù)據(jù)紊亂
>>>>>>>>>>>>>>>>>進(jìn)程數(shù)據(jù)的共享使用manager來(lái)實(shí)現(xiàn)
1 import os 2 import multiprocessing 3 import time 4 def show(num): 5 time.sleep(1) 6 print(num,os.getpid()) 7 return 'hello python{0}'.format(num) 8 9 def ret(arg): #必須有一個(gè)參數(shù) 10 print(arg,os.getpid()) #回掉函數(shù)此時(shí)顯示的arg 就是之前被執(zhí)行函數(shù)的返回值 return 'hello python{0}'.format(num) 11 12 13 if __name__=='__main__': 14 pool=multiprocessing.Pool(5) #創(chuàng)建的線(xiàn)程池?cái)?shù)量 15 for i in range(100): 16 pool.apply_async(func=show,args=(i,),callback=ret) #進(jìn)程異步使用 回調(diào)函數(shù)使用的是主進(jìn)程 17 18 pool.close() #關(guān)閉進(jìn)程 19 pool.join() #進(jìn)程池執(zhí)行完再執(zhí)行主進(jìn)程 20 21 print('process the end')>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>回調(diào)函數(shù)是依附于主線(xiàn)程執(zhí)行的 主要用于寫(xiě)日志
隨意切換進(jìn)程運(yùn)行可以使用greenlet模塊下的g.switch方法 也是作為啟動(dòng)的
1 import greenlet 2 def t1(): 3 print(125) 4 gr1.switch() 5 print('abc') 6 7 def t2(): 8 print('hahaha') 9 gr2.switch() 10 print('python') 11 gr2.switch() 12 13 gr1=greenlet.greenlet(t2) #調(diào)t2 14 gr2=greenlet.greenlet(t1) #調(diào)t1 15 16 gr1.switch() #啟動(dòng)?
>>>>>>>>>>>>>>>>>>>通過(guò)協(xié)程的方法來(lái)實(shí)現(xiàn)進(jìn)程效率的提升
1 import requests,time 2 import gevent 3 start=time.time() 4 def f(url): 5 print('GET: %s' % url) 6 resp = requests.get(url) 7 data = resp.text 8 print(len(data)) 9 10 11 gevent.joinall([ 12 gevent.spawn(f, 'https://www.python.org/'), 13 gevent.spawn(f, 'https://www.yahoo.com/'), 14 gevent.spawn(f, 'https://github.com/'), 15 ]) 16 17 print(time.time()-start)?
轉(zhuǎn)載于:https://www.cnblogs.com/wen-kang/p/9427602.html
總結(jié)
- 上一篇: mysql数据库基本操作命令
- 下一篇: day14之模块