from :http://masnun.com/2015/11/20/python-asyncio-future-task-and-the-event-loop.html

Event Loop

On any platform, when we want to do something asynchronously, it usually involves an event loop. An event loop is a loop that can register tasks to be executed, execute them, delay or even cancel them and handle different events related to these operations. Generally, we schedule multiple async functions to the event loop. The loop runs one function, while that function waits for IO, it pauses it and runs another. When the first function completes IO, it is resumed. Thus two or more functions can co-operatively run together. This the main goal of an event loop.

The event loop can also pass resource intensive functions to a thread pool for processing. The internals of the event loop is quite complex and we don’t need to worry much about it right away. We just need to remember that the event loop is the mechanism through which we can schedule our async functions and get them executed.

Futures / Tasks

If you are into Javascript too, you probably know about Promise. In Python we have similar concepts – Future/Task. A Future is an object that is supposed to have a result in the future. A Task is a subclass of Future that wraps a coroutine. When the coroutine finishes, the result of the Task is realized.

Coroutines

We discussed Coroutines in our last blog post. It’s a way of pausing a function and returning a series of values periodically. A coroutine can pause the execution of the function by using the yield yield from or await (python 3.5+) keywords in an expression. The function is paused until the yield statement actually gets a value.

Fitting Event Loop and Future/Task Together

It’s simple. We need an event loop and we need to register our future/task objects with the event loop. The loop will schedule and run them. We can add callbacks to our future/task objects so that we can be notified when a future has it’s results.

Very often we choose to use coroutines for our work. We wrap a coroutine in Future and get a Task object. When a coroutine yields, it is paused. When it has a value, it is resumed. When it returns, the Task has completed and gets a value. Any associated callback is run. If the coroutine raises an exception, the Task fails and not resolved.

So let’s move ahead and see example codes.

 
 
 
 
 

Python

 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import asyncio
 
 
@asyncio.coroutine
def slow_operation():
    # yield from suspends execution until
    # there's some result from asyncio.sleep
 
    yield from asyncio.sleep(1)
 
    # our task is done, here's the result
    return 'Future is done!'
 
 
def got_result(future):
    print(future.result())
 
 
# Our main event loop
loop = asyncio.get_event_loop()
 
# We create a task from a coroutine
task = loop.create_task(slow_operation())
 
# Please notify us when the task is complete
task.add_done_callback(got_result)
 
# The loop will close when the task has resolved
loop.run_until_complete(task)

As you can see already:

  • @asyncio.coroutine gets us the default event loop
  • loop.create_task(slow_operation()) creates a task from the coroutine returned by slow_operation()
  • task.add_done_callback(got_result) adds a callback to our task
  • loop.run_until_complete(task) runs the event loop until the task is realized. As soon as it has value, the loop terminates

The run_until_complete function is a nice way to manage the loop. Of course we could do this:

 
 
 
 
 

Python

 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import asyncio
 
 
async def slow_operation():
    await asyncio.sleep(1)
    return 'Future is done!'
 
 
def got_result(future):
    print(future.result())
 
    # We have result, so let's stop
    loop.stop()
 
 
loop = asyncio.get_event_loop()
task = loop.create_task(slow_operation())
task.add_done_callback(got_result)
 
# We run forever
loop.run_forever()

Here we make the loop run forever and from our callback, we explicitly shut it down when the future has resolved.

PYTHON ASYNCIO: FUTURE, TASK AND THE EVENT LOOP的更多相关文章

  1. python asyncio 关闭task

    import asyncio import time async def get_html(sleep_times): print("waiting") await asyncio ...

  2. 从event loop规范探究javaScript异步及浏览器更新渲染时机

    异步的思考 event loops隐藏得比较深,很多人对它很陌生.但提起异步,相信每个人都知道.异步背后的“靠山”就是event loops.这里的异步准确的说应该叫浏览器的event loops或者 ...

  3. HTML Standard系列:Event loop、requestIdleCallback 和 requestAnimationFrame

    HTML Standard系列:Event loop.requestIdleCallback 和 requestAnimationFrame - 掘金 https://juejin.im/post/5 ...

  4. [Javascript] Task queue & Event loop.

    Javascript with Chorme v8 engine works like this : For Chorme engine, v8, it has call stack. And all ...

  5. 深入Asyncio(五)Event Loop

    Event Loop loop除了处理协程间的切换与结束时的异常捕捉,还要监听socket和文件描述符.先做个小测试: >>> import asyncio >>> ...

  6. Python asyncio库的学习和使用

    因为要找工作,把之前自己搞的爬虫整理一下,没有项目经验真蛋疼,只能做这种水的不行的东西...T  T,希望找工作能有好结果. 之前爬虫使用的是requests+多线程/多进程,后来随着前几天的深入了解 ...

  7. 简单了解一下事件循环(Event Loop)

    关于我 一个有思想的程序猿,终身学习实践者,目前在一个创业团队任team lead,技术栈涉及Android.Python.Java和Go,这个也是我们团队的主要技术栈. Github:https:/ ...

  8. Python asyncio 模块

    Python 3.4 asyncio是Python 3.4版本引入的标准库,直接内置了对异步IO的支持. asyncio的编程模型就是一个消息循环.我们从asyncio模块中直接获取一个EventLo ...

  9. python——asyncio模块实现协程、异步编程

    我们都知道,现在的服务器开发对于IO调度的优先级控制权已经不再依靠系统,都希望采用协程的方式实现高效的并发任务,如js.lua等在异步协程方面都做的很强大. Python在3.4版本也加入了协程的概念 ...

随机推荐

  1. docker 使用redis

    1. 安装 centos 7 yum install  docker 2. 启动 修改配置: nano  /etc/sysconfig/docker 添加一下信息: OPTIONS='--selinu ...

  2. Win10 64位安装SQL2000(个人版)

    默认Win10上是不允许安装SQL2000的,毕竟SQL2000已经是10多年前的老软件了,但是因为它成熟稳定,相比SQL2005,SQL2008R2,SQL2012,SQL2014,体积要小的多,所 ...

  3. SqlServer数据文件增长也很快,到底是哪些表增长造成的呢?

    查询数据库中所有表的大小,哪些表的数据量较大 create table #t (name ), rows ), data ), index_size ), unused )) exec sp_MSfo ...

  4. 删除Android自带软件方法及adb remount 失败解决方案

    删除Android自带软件方法 1.在电脑上打开cmd,然后输入命令 adb remount adb shell su 2.接着就是Linux命令行模式了,输入 cd system/app 3然后输入 ...

  5. MS CRM 2011的自定义和开发(11)——插件(plugin)开发(三)

    http://www.cnblogs.com/StoneGarden/archive/2012/02/06/2340661.html MS CRM 2011的自定义和开发(11)——插件(plugin ...

  6. Silverlight开源框架SL提供便捷的二次开发银光框架

    Silverlight开发框架SilverFrame欢迎咨询 基于Silverlight4.0开发,兼容Silverlight 5.0,SQLServer2005数据库.WCF: 本框架有清爽的前端界 ...

  7. Python IDE Tools

    PyCharmhttps://www.jetbrains.com/pycharm/download/ Sublimehttp://www.sublimetext.com/

  8. TX Textcontrol 使用总结二——常见异常

    在使用Tx text control中间,我们经过会遇到在开发人员自己的电脑上我们的程序是可以正常允许的,但当部署到客户端却往往会发现一些意想不到的问题 如下所示: 未能加载文件或程序集“txtool ...

  9. xorm使用pgsql的例子

    测试表 /* Navicat Premium Data Transfer Source Server : localhost Source Server Type : PostgreSQL Sourc ...

  10. 学习C++11的一些思考和心得(1):lambda,function,bind和委托

     1.lambda表达式 lanbda表达式简单地来讲就是一个匿名函数,就是没有名称的函数,如果以前有接触过python或者erlang的人都比较熟悉这个,这个可以很方便地和STL里面的算法配合 st ...