python异步

  • 已完成:logging模块的学习
  • 接下来的目标:分为两步——要做什么和怎么做
  • requests模块的学习
  • python程序debug的方式
  • 异步
  • 网络的基本知识(做什么)

asnycio basic

https://pymotw.com/3/asyncio/index.html
app: <=interact=> event loop:

coroutines:

  • special functions that give up control to the caller without losing their state
    Q: a class-based abstraction layer for protocols and transports for writing code using callbacks instead of writing coroutines directly.

“coroutine”的两种含义:函数和对象

  • The function that defines a coroutine==a coroutine function (iscoroutinefunction() returns True).

  • The object obtained by calling a coroutine function==a coroutine object (iscoroutine() returns True).


Things a coroutine can do:

  • result = await future or result = yield from future
    • suspends the coroutine until the future is done, then returns the future’s result, or raises an exception, which will be propagated. (If the future is cancelled, it will raise a CancelledError exception.)
    • tasks ==futures
  • result = await coroutine or result = yield from coroutine
    • wait for another coroutine to produce a result
    • return expression
    • raise exception

运行cotouring

  • Call != start
  • schedule its execution.
    • await or yield from
    • ensure_future() function or AbstractEventLoop.create_task() method.
import asyncio

async def compute(x, y):
    print("Compute %s + %s ..." % (x, y))
    await asyncio.sleep(1.0)
    return x + y

async def print_sum(x, y):
    result = await compute(x, y)
    print("%s + %s = %s" % (x, y, result))

loop = asyncio.get_event_loop()
loop.run_until_complete(print_sum(1, 2))
loop.close()

**协程上下文切换**
Coroutines (and tasks) can only run when the event loop is running.

future:

a data structure representing the result of work that has not been completed yet.

Task:

a subclass of Future that knows how to wrap and manage the execution for a coroutine.

https://pymotw.com/3/asyncio/coroutines.html
coroutine function-> coroutine object
coroutine object .send()->run function code


  1. 建立一个coroutine func
  2. 建立event loop or 实例化一个特定的eventloop
    run_until_complete():用asyncio来start一个协程
  3. 从coroutine建立新的coroutine await() context 转换?
  4. earlier Python 3 -> @asyncio + yield from
  5. now: async def + await
python
@asyncio.coroutine()
def func()
    yield

Future

work not completed yet<-event loop watch for

  1. set_result(): change state
  2. await
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值