进程浅析

 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() #获取一个管道对象
13     p=Process(target=fun,args=(child_conn,))   #创建一个进程对象 导包也得是大写
14     p.start()
15 
16     print(parent_conn.recv(),id(parent_conn))
17     parent_conn.send('儿子你好')
18     p.join()

 >>>>>>>>>>>>>>>>>>>>>>>>>>>>管道对象处理进程数据的收发

 1 import multiprocessing
 2 def show(num,l):
 3     # with l:  #如果用with则默认写锁名就上锁
 4         l.acquire()  #启动锁
 5         print('hello python process %s'%num)
 6         l.release()  #释放锁
 7 
 8 if __name__=='__main__':
 9     lock=multiprocessing.Lock() #创建一个进程同步锁
10     for i in range(10):
11         p=multiprocessing.Process(target=show,args=(i,lock)).start()  #生成并启动十个进程对象

>>>>>>>>>>>>>>>>>同步锁实现进程的同步  为了避免同一时刻争抢资源造成数据紊乱

>>>>>>>>>>>>>>>>>进程数据的共享使用manager来实现

 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): #必须有一个参数
10     print(arg,os.getpid()) #回掉函数此时显示的arg 就是之前被执行函数的返回值    return 'hello python{0}'.format(num)
11 
12 
13 if __name__=='__main__':
14     pool=multiprocessing.Pool(5)  #创建的线程池数量
15     for i in range(100):
16         pool.apply_async(func=show,args=(i,),callback=ret)  #进程异步使用  回调函数使用的是主进程
17 
18     pool.close()  #关闭进程
19     pool.join()   #进程池执行完再执行主进程
20 
21     print('process the end')

>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>回调函数是依附于主线程执行的 主要用于写日志

随意切换进程运行可以使用greenlet模块下的g.switch方法 也是作为启动的

 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)  #调t2
14 gr2=greenlet.greenlet(t1)  #调t1
15 
16 gr1.switch()  #启动

>>>>>>>>>>>>>>>>>>>通过协程的方法来实现进程效率的提升

 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)
原文地址:https://www.cnblogs.com/wen-kang/p/9427602.html