Home Backend Development Python Tutorial Detailed explanation of the use of asyncio package for concurrent processing in Python_python

Detailed explanation of the use of asyncio package for concurrent processing in Python_python

Apr 08, 2018 am 11:43 AM
asyncio python deal with

本篇文章主要介绍了Python中的并发处理之asyncio包使用的详解,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

导语:本文章记录了本人在学习Python基础之控制流程篇的重点知识及个人心得,打算入门Python的朋友们可以来一起学习并交流。

本文重点:

1、了解asyncio包的功能和使用方法;
2、了解如何避免阻塞型调用;
3、学会使用协程避免回调地狱。

一、使用asyncio包做并发编程

1、并发与并行

并发:一次处理多件事。
并行:一次做多件事。
并发用于制定方案,用来解决可能(但未必)并行的问题。并发更好。

2、asyncio概述

了解asyncio的4个特点:

  1. asyncio包使用事件循环驱动的协程实现并发。

  2. 适合asyncio API的协程在定义体中必须使用yield from,而不能使用yield。

  3. 使用asyncio处理的协程,需在定义体上使用@asyncio.coroutine装饰。装饰的功能在于凸显协程,同时当协程不产出值,协程会被垃圾回收。

  4. Python3.4起,asyncio包只直接支持TCP和UDP协议。如果想使用asyncio实现HTTP客户端和服务器时,常使用aiohttp包。

在协程中使用yield from需要注意两点:

  1. 使用yield froml链接的多个协程最终必须由不是协程的调用方驱动,调用方显式或隐式在最外层委派生成器上调用next()函数或 .send()方法。

  2. 链条中最内层的子生成器必须是简单的生成器(只使用yield)或可迭代的对象。

但在asyncio包的API中使用yield from还需注意两个细节:

  1. asyncio包中编写的协程链条始终通过把最外层委派生成器传给asyncio包API中的某个函数驱动,例如loop.run_until_complete()。即不通过调用next()函数或 .send()方法驱动协程。

  2. 编写的协程链条最终通过yield from把职责委托给asyncio包中的某个协程函数或协程方法。即最内层的子生成器是库中真正执行I/O操作的函数,而不是我们自己编写的函数。

实例——通过asyncio包和协程以动画形式显示文本式旋转指针:

import asyncio
import itertools
import sys

@asyncio.coroutine # 交给 asyncio 处理的协程要使用 @asyncio.coroutine 装饰
def spin(msg):
  for char in itertools.cycle('|/-\\'):
    status = char + ' ' + msg
    print(status)
    try:
      yield from asyncio.sleep(.1) # 使用 yield from asyncio.sleep(.1) 代替 time.sleep(.1),这样的休眠不会阻塞事件循环。
    except asyncio.CancelledError: # 如果 spin 函数苏醒后抛出 asyncio.CancelledError 异常,其原因是发出了取消请求,因此退出循环。
      break

@asyncio.coroutine
def slow_function(): # slow_function 函数是协程,在用休眠假装进行 I/O 操作时,使用 yield from 继续执行事件循环。
  # 假装等待I/O一段时间
  yield from asyncio.sleep(3) # yield from asyncio.sleep(3) 表达式把控制权交给主循环,在休眠结束后恢复这个协程。
  return 42

@asyncio.coroutine
def supervisor(): # supervisor 函数也是协程
  spinner = asyncio.async(spin('thinking!')) # asyncio.async(...) 函数排定 spin 协程的运行时间,使用一个 Task 对象包装spin 协程,并立即返回。
  print('spinner object:', spinner)
  result = yield from slow_function() # 驱动 slow_function() 函数。结束后,获取返回值。
# 同时,事件循环继续运行,因为slow_function 函数最后使用 yield from asyncio.sleep(3) 表达式把控制权交回给了主循环。
  spinner.cancel() # Task 对象可以取消;取消后会在协程当前暂停的 yield 处抛出 asyncio.CancelledError 异常。协程可以捕获这个异常,也可以延迟取消,甚至拒绝取消。
  return result

if __name__ == '__main__':
  loop = asyncio.get_event_loop() # 获取事件循环的引用
  result = loop.run_until_complete(supervisor()) # 驱动 supervisor 协程,让它运行完毕;这个协程的返回值是这次调用的返回值。
  loop.close()
  print('Answer:', result)
Copy after login

3、线程与协程对比

线程:调度程序在任何时候都能中断线程。必须记住保留锁。去保护程序中的重要部分,防止多步操作在执行的过程中中断,防止数据处于无效状态。

协程:默认会做好全方位保护,以防止中断。对协程来说无需保留锁,在多个线程之间同步操作,协程自身就会同步,因为在任意时刻只有一个协程运行。

4、从期物、任务和协程中产出

在asyncio包中,期物和协程关系紧密,因为可以使用yield from从asyncio.Future对象中产出结果。这意味着,如果foo是协程函数,抑或是返回Future或Task实例的普通函数,那么可以这样写:res=yield from foo()。这是asyncio包中很多地方可以互换协程与期物的原因之一。

二、避免阻塞型调用

1、有两种方法能避免阻塞型调用中止整个应用程序的进程:

  1. 在单独的线程中运行各个阻塞型操作。

  2. 把每个阻塞型操作转换成非阻塞的异步调用。

使用多线程处理大量连接时将耗费过多的内存,故此通常使用回调来实现异步调用。

2、使用Executor对象防止阻塞事件循环:

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

@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)
Copy after login

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

三、从回调到期物和协程

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

Python 中的回调地狱:

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)
Copy after login

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

@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 表达式把它激活
Copy after login

四、使用asyncio包编写服务器

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

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

Related recommendations:

Detailed explanation of how Python uses the asyncio package to handle concurrency

The advantages and disadvantages of asyncio


The above is the detailed content of Detailed explanation of the use of asyncio package for concurrent processing in Python_python. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

How is the GPU support for PyTorch on CentOS How is the GPU support for PyTorch on CentOS Apr 14, 2025 pm 06:48 PM

Enable PyTorch GPU acceleration on CentOS system requires the installation of CUDA, cuDNN and GPU versions of PyTorch. The following steps will guide you through the process: CUDA and cuDNN installation determine CUDA version compatibility: Use the nvidia-smi command to view the CUDA version supported by your NVIDIA graphics card. For example, your MX450 graphics card may support CUDA11.1 or higher. Download and install CUDAToolkit: Visit the official website of NVIDIACUDAToolkit and download and install the corresponding version according to the highest CUDA version supported by your graphics card. Install cuDNN library:

Python vs. JavaScript: Community, Libraries, and Resources Python vs. JavaScript: Community, Libraries, and Resources Apr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

Detailed explanation of docker principle Detailed explanation of docker principle Apr 14, 2025 pm 11:57 PM

Docker uses Linux kernel features to provide an efficient and isolated application running environment. Its working principle is as follows: 1. The mirror is used as a read-only template, which contains everything you need to run the application; 2. The Union File System (UnionFS) stacks multiple file systems, only storing the differences, saving space and speeding up; 3. The daemon manages the mirrors and containers, and the client uses them for interaction; 4. Namespaces and cgroups implement container isolation and resource limitations; 5. Multiple network modes support container interconnection. Only by understanding these core concepts can you better utilize Docker.

MiniOpen Centos compatibility MiniOpen Centos compatibility Apr 14, 2025 pm 05:45 PM

MinIO Object Storage: High-performance deployment under CentOS system MinIO is a high-performance, distributed object storage system developed based on the Go language, compatible with AmazonS3. It supports a variety of client languages, including Java, Python, JavaScript, and Go. This article will briefly introduce the installation and compatibility of MinIO on CentOS systems. CentOS version compatibility MinIO has been verified on multiple CentOS versions, including but not limited to: CentOS7.9: Provides a complete installation guide covering cluster configuration, environment preparation, configuration file settings, disk partitioning, and MinI

How to operate distributed training of PyTorch on CentOS How to operate distributed training of PyTorch on CentOS Apr 14, 2025 pm 06:36 PM

PyTorch distributed training on CentOS system requires the following steps: PyTorch installation: The premise is that Python and pip are installed in CentOS system. Depending on your CUDA version, get the appropriate installation command from the PyTorch official website. For CPU-only training, you can use the following command: pipinstalltorchtorchvisiontorchaudio If you need GPU support, make sure that the corresponding version of CUDA and cuDNN are installed and use the corresponding PyTorch version for installation. Distributed environment configuration: Distributed training usually requires multiple machines or single-machine multiple GPUs. Place

How to choose the PyTorch version on CentOS How to choose the PyTorch version on CentOS Apr 14, 2025 pm 06:51 PM

When installing PyTorch on CentOS system, you need to carefully select the appropriate version and consider the following key factors: 1. System environment compatibility: Operating system: It is recommended to use CentOS7 or higher. CUDA and cuDNN:PyTorch version and CUDA version are closely related. For example, PyTorch1.9.0 requires CUDA11.1, while PyTorch2.0.1 requires CUDA11.3. The cuDNN version must also match the CUDA version. Before selecting the PyTorch version, be sure to confirm that compatible CUDA and cuDNN versions have been installed. Python version: PyTorch official branch

Python: Automation, Scripting, and Task Management Python: Automation, Scripting, and Task Management Apr 16, 2025 am 12:14 AM

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.

See all articles