协程

Python连载38-协程、可迭代、迭代器、生产者消费者模型

匿名 (未验证) 提交于 2019-12-02 22:51:30
一、生产者消费者模型 import multiprocessing from time import ctime def consumer ( input_q ): print ( "Into consumer:" , ctime ()) while True : #处理项 item = input_q . get () print ( "pull" , item , "out of q" )#此处替换为有用的工作 input_q . task_done ()#发出信号通知任务完成 print ( "Out of consumer:" , ctime ()) #此句未执行,因为q.join()收集到四个task_done()信号后,主进程启动 def producer ( sequence , output_q ): print ( "Into producer:" , ctime ()) for item in sequence : output_q . put ( item ) print ( "put" , item , "into_q" ) print ( "Out of producer:" , ctime ()) #建立进程 if __name__ == "__main__" : q = multiprocessing . JoinableQueue ()

python3.6异步IO包asyncio部分核心源码思路梳理

匿名 (未验证) 提交于 2019-12-02 22:51:30
关于python异步编程的演进过程,两篇文章阐述得妥妥当当,明明白白。 中文资料:https://mp.weixin.qq.com/s?__biz=MzIxMjY5NTE0MA==&mid=2247483720&idx=1&sn=f016c06ddd17765fd50b705fed64429c 英文资料:http://aosabook.org/en/500L/a-web-crawler-with-asyncio-coroutines.html 其实中文资料就是参考的英文资料,英文资料是开源书《 500 Lines or Less 》中的一个主题章节,整书地址:https://github.com/aosabook/500lines python的asyncio源码的核心思路其实跟基于生成器的协程异步编程思路大体一致,只是前者做了大量的代码优化和功能扩充。所以对照生成器协程代码来理解asyncio是很有帮助的。以下的这一小段代码就是采用基于生成器的协程的异步编程方式写的一个小爬虫案例,来自上述中文资料,asyncio的核心代码的思路大体上能从这段代码中找到原型。 该脚本命名为:yield_from.py import socket from selectors import DefaultSelector, EVENT_READ, EVENT_WRITE selector =

python_高级进阶(5)协程_事件

匿名 (未验证) 提交于 2019-12-02 22:51:30
import queue q = queue . Queue ( 3 ) q . put ( 1 ) q . put ( 2 ) q . put ( 3 ) q . put ( 4 ) print ( q . get ()) print ( q . get ()) print ( q . get ()) print ( q . get ( block = False )) q . get ( timeout = 2 ) # 阻塞2s 还没有值直接报错 结果: #1 #2 #3 ##第二种、后进先出 Lifo 堆栈 q = queue . LifoQueue ( 4 ) q . put ( 1 ) q . put ( 2 ) q . put ( 'alex' ) q . put ( '太白' ) print ( q . get ()) print ( q . get ()) print ( q . get ()) print ( q . get ()) 结果: 太白 alex 2 1 q = queue . PriorityQueue ( 4 ) q . put (( 5 , '元宝' )) q . put ((- 2 , '狗狗' )) q . put (( 0 , '李业' )) print ( q . get ()) print ( q . get ()) print ( q

python多任务――协程的使用

匿名 (未验证) 提交于 2019-12-02 22:51:30
import time def test1(): while True: print("--1--") time.sleep(0.5) yield None def test2(): while True: print("--2--") time.sleep(0.5) yield None if __name__ == "__main__": t1 = test1() t2 = test2() while True: next(t1) next(t2) 如果没有安装,则 pip install greenlet from greenlet import greenlet import time def test1(): while True: print("---A---") gr2.switch() time.sleep(0.5) def test2(): while True: print("---b---") gr1.switch() time.sleep(0.5) gr1 = greenlet(test1) gr2 = greenlet(test2) gr1.switch() 首先使用 pip install gevent 进行安装 gevent是对greenlet的再次封装,使用起来更加简便,当有耗时操作时会自动切换到其他协程。gevent封装了常用的耗时操作

python之 yield --- “协程”

匿名 (未验证) 提交于 2019-12-02 22:51:30
在编程中我们经常会用到列表,以前使用列表时需要声明和初始化,在数据量比较大的时候也需要把列表完整生产出来,例如要存放1000给数据,需要准备长度1000的列表,这样计算机就需要准备内存放置这个列表,在Python中,这种一边循环一边计算的机制,称为生成器:generator,这个功能在列表使用时比较节省空间,使用方法: g=(i*2 for i in range(10)) data=g.__next__() print(d) 取列表时data=g.__next__(),此时才去生成。 应用:生成斐波拉契数列 def fig(num): n,a,b=0,0,1 while n<num: yield b a,b=b,a+b n+=1 return 'done' fig(10) 定义长度为10的数列 fig(10) for i in range(10): try: x=next(g) print(x) except StopIteration as e: print('error %s' % e.value) break 运行结果: 1 1 2 3 5 8 13 21 34 55 这里,最难理解的就是generator和函数的执行流程不一样。函数是顺序执行,遇到 return 语句或者最后一行函数语句就返回。而变成generator的函数,在每次调用 next() 的时候执行,遇到

Python高级知识归纳

匿名 (未验证) 提交于 2019-12-02 22:51:08
本文主要归纳3个内容: Python协程 Python多线程 Python多进程 本部分内容参考: 廖雪峰 - Python协程 协程,又称微线程,纤程。英文名Coroutine 协程看上去也是子程序,但执行过程中,在子程序内部可中断,然后转而执行别的子程序,在适当的时候再返回来接着执行。(不同于函数调用) 协程相对于多线程的优势: 协程的执行效率高于多线程 协程不需要锁机制:因为只有一个线程,所以不存在同时写变量冲突 多进程+协程,既充分利用多核CPU,又充分发挥协程的高效率,可获得极高的性能 【示例】生产者消费者模型的协程实现: def consumer(): r = '' while True: n = yield r if not n: return print('[CONSUMER] Consuming %s...' % n) r = '200 OK' def produce(c): c.send(None) n = 0 while n < 5: n = n + 1 print('[PRODUCER] Producing %s...' % n) r = c.send(n) print('[PRODUCER] Consumer return: %s' % r) c.close() c = consumer() produce(c) 执行结果: [PRODUCER]

Unity常用协程功能封装

天涯浪子 提交于 2019-12-02 22:30:28
# 1.前言 unity开发过程中,经常用到一些特定的协程功能,比如延时触发、等待触发、重复操作等。unity自带Invoke以及InvokeRepeating方法,但这些方法均采用反射机制,性能消耗,而且代码混淆时极其容易出错。所以再次对这些功能做以下简单封装。方便后续使用。 # 2.CoroutineJobCenter CoroutineJobCenter封装了需要的基本方法。 ## 2.1 延时触发 延时一定事件触发。 ```csharp public IEnumerator StartJobDelayed(float delayedTime, Action action) { yield return new WaitForSeconds(delayedTime); if (action != null) { action(); } } public IEnumerator StartJobDelayed<T>(float delayedTime, Action<T> action, T t) { yield return new WaitForSeconds(delayedTime); if (action != null) { action(t); } } ``` ## 2.2 等待触发 等待某一条件返回true时触发,采用unity自带的WaitUntil类。 ``

IO多路复用丶基于IO多路复用+socket实现并发请求丶协程

匿名 (未验证) 提交于 2019-12-02 22:11:45
一丶IO多路复用   IO多路复用指:通过一种机制,可以监视多个描述符,一旦某个描述符就绪(一般是读就绪或者写就绪),能够通知程序进行相应的读写操作   IO多路复用作用:     检测多个socket是否已经发生变化(是否已经连接成功/是否已经获取数据)(可读/可写)     操作系统检测socket是否发生变化有三种模式:       select:最多1024个socket,循环去检测       poll:不限制监听socket个数,循环去检测(水平触发)       epoll:不限制监听socket个数:回调方式(边缘触发).     Python模块:       select.select       select.epoll   Python中有一个select模块,其中提供了:select丶poll丶epoll三个方法,分别调用系统的select,poll,epoll从而实现IO多路复用 二丶基于IO多路复用+socket实现并发请求(一个线程100个请求)   当我们需要向百度发送请求搜索三个关键字,我们改怎么办呢?   单线程解决并发: 方式一: key_list = ['alex','db','sb'] for item in key_list: ret = requests.get('https://www.baidu.com/s?wd=%s'

在爬虫中使用单线程异步协程,包含单任务和多任务,以及数据解析使用回调函数

混江龙づ霸主 提交于 2019-12-02 19:56:47
aiohttp 简介 aiohttp 可以实现单线程并发IO操作,用他来代替非异步模块request来发送请求,请求中的ua,headers,和参数都可以添加,添加方法如下: 环境安装 pip install aiohttp aiohttp使用 1.发起请求 async def fetch(): async with aiohttp.ClientSession() as session: async with session.get('https://www.baidu.com') as resposne: print(await resposne.text()) loop = asyncio.get_event_loop() tasks = [fetch(),] loop.run_until_complete(asyncio.wait(tasks)) 2.添加请求参数的方法: params = {'key': 'value', 'page': 10} async def fetch(): async with aiohttp.ClientSession() as session: async with session.get('https://www.baidu.com/s',params=params) as resposne: print(await resposne.url

C++ coroutine

风格不统一 提交于 2019-12-02 19:40:20
C++20 协程 本文主要来源于 https://lewissbaker.github.io/2017/09/25/coroutine-theory https://blog.panicsoftware.com/coroutines-introduction/ https://kirit.com/How%20C%2B%2B%20coroutines%20work/My%20first%20coroutine https://en.cppreference.com/w/cpp/language/coroutines 协程 A coroutine is a generalization of a function that allows the function to be suspended and then later resumed. It generalizes the operations of a function by separating out some of the steps performed in the Call and Return operations into three extra operations: Suspend , Resume and Destroy. Since coroutines can be suspended without