Python中的并发处理之asyncio包使用的详解_python


当前第2页 返回上一页

使用loop.run_in_executor把阻塞的作业(例如保存文件)委托给线程池做。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

@asyncio.coroutine

def download_one(cc, base_url, semaphore, verbose):

  try:

    with (yield from semaphore):

      image = yield from get_flag(base_url, cc)

  except web.HTTPNotFound:

    status = HTTPStatus.not_found

    msg = 'not found'

  except Exception as exc:

    raise FetchError(cc) from exc

  else:

    loop = asyncio.get_event_loop() # 获取事件循环对象的引用

    loop.run_in_executor(None, # None 使用默认的 TrreadPoolExecutor 实例

        save_flag, image, cc.lower() + '.gif') # 传入可调用对象

    status = HTTPStatus.ok

    msg = 'OK'

 

  if verbose and msg:

    print(cc, msg)

 

  return Result(status, cc)

asyncio 的事件循环背后维护一个 ThreadPoolExecutor 对象,我们可以调用 run_in_executor 方法, 把可调用的对象发给它执行。

三、从回调到期物和协程

回调地狱:如果一个操作需要依赖之前操作的结果,那就得嵌套回调。

Python 中的回调地狱:

1

2

3

4

5

6

7

8

9

10

11

12

def stage1(response1):

  request2 = step1(response1)

  api_call2(request2, stage2)

 

def stage2(response2):

  request3 = step2(response2)

  api_call3(request3, stage3)

 

def stage3(response3):

  step3(response3)

 

api_call1(request1, step1)

使用 协程 和 yield from 结构做异步编程,无需用回调:

1

2

3

4

5

6

7

8

9

10

11

@asyncio.coroutine

def three_stages(request1):

  response1 = yield from api_call1()

  request2 = step1(response1)

  response2 = yield from api_call2(request2)

  request3 = step2(response2)

  response3 = yield from api_call3(request3)

  step3(response3)

 

loop.create_task(three_stages(request1))

# 协程不能直接调用,必须用事件循环显示指定协程的执行时间,或者在其他排定了执行时间的协程中使用 yield from 表达式把它激活

四、使用asyncio包编写服务器

  1. 使用asyncio包能实现TCP和HTTP服务器

  2. Web服务将成为asyncio包的重要使用场景。

相关推荐:

详解Python使用asyncio包处理并发的方法

asyncio 的优势与缺点


以上就是Python中的并发处理之asyncio包使用的详解_python的详细内容,更多文章请关注木庄网络博客!!

返回前面的内容

相关阅读 >>

基于Python2基础的实例详解

Python实现翻译软件

关于Python下如何实现rsa的加密解密以及签名与验证功能的实例分析

Python怎么打印字符

Python注释以什么符号开始

Python中整型的基本介绍(代码示例)

Python list排序的两种方法及实例

Python语法基础详解

Python中数据类型时间的介绍(附代码)

Python如何使用getpass库读取密码的方法介绍

更多相关阅读请进入《Python》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...