标签:utf-8 openstack coroutine 内核 input maker mon time() 速度
concurrent.futures —Launching parallel tasks concurrent.futures模块同时提供了进程池和线程池,它是将来的使用趋势,同样我们之前学习的进程池Pool和threadpool模块也可以使用。
对进程池疑惑的可以参阅:32进程池与回调函数http://www.cnblogs.com/liluning/p/7445457.html
对threadpool模块疑惑的可以看我闲暇时写的一段代码:(因为本人也不了解这个模块,代码里写的也是自己想当然的,如有问题请自行查阅资料)
#pip3 install threadpool #需下载 import threadpool import requests import re import os #爬取网页 def get_page(url) : pattern = re.compile(r‘<dd>.*?board-index.*?>(\d+)<.*?title="(.*?)".*?star.*?>(.*?)<.*?releasetime.*?>(.*?)<‘, re.S) response = requests.get(url) if response.status_code == 200 : #status_code请求的状态码200为正常 return (response.text,pattern,url) #信息处理 def parse_page(info) : page_content,pattern,url = info print(‘<%s> parse [%s]‘% (os.getpid(), url)) res = re.findall(pattern,page_content) dic_l = [] for item in res: dic = { ‘index‘:item[0], ‘title‘:item[1], ‘actor‘:item[2].strip()[3:], ‘time‘:item[3][5:] } dic_l.append(dic) print(dic) with open(‘movie_info.txt‘,‘a‘,encoding=‘utf-8‘) as f : for i in range(len(dic_l)) : parse_res = (‘index:%s title:%s actor:%s time:%s\n‘ %(dic_l[i][‘index‘],dic_l[i][‘title‘],dic_l[i][‘actor‘],dic_l[i][‘time‘])) f.write(parse_res) if __name__ == ‘__main__‘: urls = [ ‘http://maoyan.com/board/7‘, ‘http://maoyan.com/board/6‘, ‘http://maoyan.com/board/1‘, ‘http://maoyan.com/board/2‘, ‘http://maoyan.com/board/4‘, ] t = threadpool.ThreadPool(4) #创建线程池 for url in urls : res = threadpool.makeRequests(get_page,urls,parse_page(get_page(url))) #参数:执行函数,参数,回调函数 [t.putRequest(req) for req in res] t.wait()
一、concurrent.futures模块
1、官方文档
https://docs.python.org/dev/library/concurrent.futures.html#module-concurrent.futures
2、ProcessPoolExecutor(进程池)与ThreadPoolExecutor(线程池)
(进程池类与线程池类的方法使用等各方面基本相同)
1)导入
from concurrent.futures import ProcessPoolExecutor,ThreadPoolExecutor
2)创建
p = ProcessPoolExecutor(num) #创建进程池 t = ThreadPoolExecutor(num) #创建线程池
3)参数
num:要创建的进程数或线程数,如果省略,进程数将默认使用cpu_count()的值,线程数将默认使用cpu_count()*5的值
4)主要方法
submit(fn, *args, **kwargs):在一个池工作进程中执行执行fn(args kwargs)执行,并返回一个表示可调用的执行的Future对象 map(func, *iterables, timeout=None, chunksize=1): shutdown(wait=True):执行结束释放资源
3、应用
1)进程池
from concurrent.futures import ProcessPoolExecutor import os,time def task(n): print(‘%s is running‘ %os.getpid()) time.sleep(2) return n**2 if __name__ == ‘__main__‘: p=ProcessPoolExecutor() l=[] start=time.time() for i in range(10): obj=p.submit(task,i) l.append(obj) p.shutdown() print(‘=‘*30) print([obj for obj in l]) print([obj.result() for obj in l]) print(time.time()-start)
2)线程池
from concurrent.futures import ThreadPoolExecutor import threading import os,time def task(n): print(‘%s:%s is running‘ %(threading.currentThread().getName(),os.getpid())) time.sleep(2) return n**2 if __name__ == ‘__main__‘: p=ThreadPoolExecutor() l=[] start=time.time() for i in range(10): obj=p.submit(task,i) l.append(obj) p.shutdown() print(‘=‘*30) print([obj.result() for obj in l]) print(time.time()-start)
3)同步执行
from concurrent.futures import ProcessPoolExecutor,ThreadPoolExecutor import os,time,random def task(n): print(‘%s is running‘ %os.getpid()) time.sleep(2) return n**2 if __name__ == ‘__main__‘: p=ProcessPoolExecutor() start=time.time() for i in range(10): res=p.submit(task,i).result() print(res) print(‘=‘*30) print(time.time()-start)
4、回调函数
不懂回调函数的看本章节首部有链接
from concurrent.futures import ThreadPoolExecutor import requests, os, time from threading import currentThread def get_page(url): print(‘%s:<%s> is getting [%s]‘ %(currentThread().getName(),os.getpid(),url)) response=requests.get(url) time.sleep(2) return {‘url‘:url,‘text‘:response.text} def parse_page(res): res=res.result() #注意值 print(‘%s:<%s> parse [%s]‘ %(currentThread().getName(),os.getpid(),res[‘url‘])) with open(‘db.txt‘,‘a‘) as f: parse_res=‘url:%s size:%s\n‘ %(res[‘url‘],len(res[‘text‘])) f.write(parse_res) if __name__ == ‘__main__‘: p=ThreadPoolExecutor() urls = [ ‘https://www.baidu.com‘, ‘http://www.openstack.org‘, ‘https://www.python.org‘, ‘http://www.sina.com.cn/‘ ] for url in urls: p.submit(get_page, url).add_done_callback(parse_page) #add_done_callback()回调函数 p.shutdown() print(‘主‘,os.getpid())
5、map方法
map有疑惑可以阅览:19、内置函数和匿名函数http://www.cnblogs.com/liluning/p/7280832.html
from concurrent.futures import ProcessPoolExecutor import os,time def task(n): print(‘%s is running‘ %os.getpid()) time.sleep(2) return n**2 if __name__ == ‘__main__‘: p=ProcessPoolExecutor() obj=p.map(task,range(10)) p.shutdown() print(‘=‘*30) print(list(obj))
二、协程概念
1、定义
是单线程下的并发,又称微线程,纤程。英文名Coroutine。一句话说明什么是线程:协程是一种用户态的轻量级线程,即协程是由用户程序自己控制调度的。
2、注意
1)python的线程属于内核级别的,即由操作系统控制调度(如单线程遇到io或执行时间过长就会被迫交出cpu执行权限,切换其他线程运行)
2)单线程内开启协程,一旦遇到io,就会从应用程序级别(而非操作系统)控制切换,以此来提升效率(!!!非io操作的切换与效率无关)
3、优点
1) 协程的切换开销更小,属于程序级别的切换,操作系统完全感知不到,因而更加轻量级
2) 单线程内就可以实现并发的效果,最大限度地利用cpu
4、缺点
1) 协程的本质是单线程下,无法利用多核,可以是一个程序开启多个进程,每个进程内开启多个线程,每个线程内开启协程
2) 协程指的是单个线程,因而一旦协程出现阻塞,将会阻塞整个线程
5、总结
1)必须在只有一个单线程里实现并发
2)修改共享数据不需加锁
3)用户程序里自己保存多个控制流的上下文栈
附加:一个协程遇到IO操作自动切换到其它协程(如何实现检测IO,yield、greenlet都无法实现,就用到了gevent模块(select机制))
三、greenlet模块
如果我们在单个线程内有20个任务,要想实现在多个任务之间切换,使用yield生成器的方式过于麻烦(需要先得到初始化一次的生成器,然后再调用send。。。非常麻烦),而使用greenlet模块可以非常简单地实现这20个任务直接的切换
生成器:18、迭代器和生成器http://www.cnblogs.com/liluning/p/7274862.html
1、安装
pip3 install greenlet
2、使用
from greenlet import greenlet def eat(name): print(‘%s eat 1‘ %name) g2.switch(‘egon‘) print(‘%s eat 2‘ %name) g2.switch() def play(name): print(‘%s play 1‘ %name) g1.switch() print(‘%s play 2‘ %name) g1=greenlet(eat) g2=greenlet(play) g1.switch(‘egon‘)#可以在第一次switch时传入参数,以后都不需要
3、单纯的切换(在没有io的情况下或者没有重复开辟内存空间的操作),反而会降低程序的执行速度
#顺序执行 import time def f1(): res=1 for i in range(100000000): res+=i def f2(): res=1 for i in range(100000000): res*=i start=time.time() f1() f2() stop=time.time() print(‘run time is %s‘ %(stop-start)) #10.985628366470337 #切换 from greenlet import greenlet import time def f1(): res=1 for i in range(100000000): res+=i g2.switch() def f2(): res=1 for i in range(100000000): res*=i g1.switch() start=time.time() g1=greenlet(f1) g2=greenlet(f2) g1.switch() stop=time.time() print(‘run time is %s‘ %(stop-start)) # 52.763017892837524
单线程里的这20个任务的代码通常会既有计算操作又有阻塞操作,我们完全可以在执行任务1时遇到阻塞,就利用阻塞的时间去执行任务2。。。。如此,才能提高效率,这就用到了Gevent模块。
四、Gevent模块
1、安装
pip3 install gevent
Gevent 是一个第三方库,可以轻松通过gevent实现并发同步或异步编程,在gevent中用到的主要模式是Greenlet, 它是以C扩展模块形式接入Python的轻量级协程。 Greenlet全部运行在主程序操作系统进程的内部,但它们被协作式地调度。
2、用法
g1=gevent.spawn(func,1,,2,3,x=4,y=5)创建一个协程对象g1,spawn括号内第一个参数是函数名,如eat,后面可以有多个参数,可以是位置实参或关键字实参,都是传给函数eat的 g2=gevent.spawn(func2) g1.join() #等待g1结束 g2.join() #等待g2结束 #或者上述两步合作一步:gevent.joinall([g1,g2]) g1.value#拿到func1的返回值
3、遇到IO阻塞时会自动切换任务
import gevent def eat(name): print(‘%s eat 1‘ %name) gevent.sleep(2) print(‘%s eat 2‘ %name) def play(name): print(‘%s play 1‘ %name) gevent.sleep(1) print(‘%s play 2‘ %name) g1=gevent.spawn(eat,‘egon‘) g2=gevent.spawn(play,name=‘egon‘) g1.join() g2.join() #或者gevent.joinall([g1,g2]) print(‘主‘)
上例gevent.sleep(2)模拟的是gevent可以识别的io阻塞,而time.sleep(2)或其他的阻塞,gevent是不能直接识别的需要用下面一行代码,打补丁,就可以识别了from gevent import monkey;monkey.patch_all()必须放到被打补丁者的前面,如time,socket模块之前或者我们干脆记忆成:要用gevent,需要将from gevent import monkey;monkey.patch_all()放到文件的开头
from gevent import monkey;monkey.patch_all() import gevent import time def eat(): print(‘eat food 1‘) time.sleep(2) print(‘eat food 2‘) def play(): print(‘play 1‘) time.sleep(1) print(‘play 2‘) g1=gevent.spawn(eat) g2=gevent.spawn(play_phone) gevent.joinall([g1,g2]) print(‘主‘)
4、Gevent的同步与异步
from gevent import spawn,joinall,monkey;monkey.patch_all() import time def task(pid): """ Some non-deterministic task """ time.sleep(0.5) print(‘Task %s done‘ % pid) def synchronous(): for i in range(10): task(i) def asynchronous(): g_l=[spawn(task,i) for i in range(10)] joinall(g_l) if __name__ == ‘__main__‘: print(‘Synchronous:‘) synchronous() print(‘Asynchronous:‘) asynchronous() #上面程序的重要部分是将task函数封装到Greenlet内部线程的gevent.spawn。 初始化的greenlet列表存放在数组threads中,此数组被传给gevent.joinall 函数,后者阻塞当前流程,并执行所有给定的greenlet。执行流程只会在 所有greenlet执行完后才会继续向下走。
5、Gevent实现爬虫
from gevent import monkey;monkey.patch_all() import gevent import requests import time def get_page(url): print(‘GET: %s‘ %url) response=requests.get(url) if response.status_code == 200: print(‘%d bytes received from %s‘ %(len(response.text),url)) start_time=time.time() g1=gevent.spawn(get_page, ‘https://www.python.org/‘) g2=gevent.spawn(get_page, ‘https://www.yahoo.com/‘) g3=gevent.spawn(get_page, ‘https://github.com/‘) gevent.joinall([g1,g2,g3]) stop_time=time.time() print(‘run time is %s‘ %(stop_time-start_time))
6、gevent实现单线程下的socket并发
通过gevent实现单线程下的socket并发(from gevent import monkey;monkey.patch_all()一定要放到导入socket模块之前,否则gevent无法识别socket的阻塞)
from gevent import monkey;monkey.patch_all() from socket import * import gevent #如果不想用money.patch_all()打补丁,可以用gevent自带的socket # from gevent import socket # s=socket.socket() def server(server_ip,port): s=socket(AF_INET,SOCK_STREAM) s.setsockopt(SOL_SOCKET,SO_REUSEADDR,1) s.bind((server_ip,port)) s.listen(5) while True: conn,addr=s.accept() gevent.spawn(talk,conn,addr) def talk(conn,addr): try: while True: res=conn.recv(1024) print(‘client %s:%s msg: %s‘ %(addr[0],addr[1],res)) conn.send(res.upper()) except Exception as e: print(e) finally: conn.close() if __name__ == ‘__main__‘: server(‘127.0.0.1‘,8080)
from socket import * client=socket(AF_INET,SOCK_STREAM) client.connect((‘127.0.0.1‘,8080)) while True: msg=input(‘>>: ‘).strip() if not msg:continue client.send(msg.encode(‘utf-8‘)) msg=client.recv(1024) print(msg.decode(‘utf-8‘))
7、多协程发送多个客户端
from gevent import monkey;monkey.patch_all() import gevent from socket import * def talk(conn,addr): while True: data=conn.recv(1024) print(‘%s:%s %s‘ %(addr[0],addr[1],data)) conn.send(data.upper()) conn.close() def server(ip,port): s = socket(AF_INET, SOCK_STREAM) s.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1) s.bind((ip,port)) s.listen(5) while True: conn,addr=s.accept() gevent.spawn(talk,conn,addr) s.close() if __name__ == ‘__main__‘: server(‘127.0.0.1‘, 8088)
from multiprocessing import Process from socket import * def client(server_ip,server_port): client=socket(AF_INET,SOCK_STREAM) client.connect((server_ip,server_port)) while True: client.send(‘hello‘.encode(‘utf-8‘)) msg=client.recv(1024) print(msg.decode(‘utf-8‘)) if __name__ == ‘__main__‘: for i in range(500): p=Process(target=client,args=(‘127.0.0.1‘,8088)) p.start()
标签:utf-8 openstack coroutine 内核 input maker mon time() 速度
原文地址:http://www.cnblogs.com/liluning/p/7459454.html