📅  最后修改于: 2023-12-03 15:25:33.559000             🧑  作者: Mango
Asynchronous programming is a programming paradigm that allows the execution of tasks in a non-blocking way. This can be particularly useful in situations where the processing time of a task is unpredictable or when multiple tasks need to be executed concurrently.
In Python, asynchronous programming can be implemented using several different frameworks and libraries, including:
Here is an example of using asyncio to write a simple program that fetches multiple web pages concurrently:
import asyncio
import aiohttp
async def fetch(session, url):
async with session.get(url) as response:
return await response.text()
async def fetch_all(urls):
async with aiohttp.ClientSession() as session:
tasks = []
for url in urls:
task = asyncio.ensure_future(fetch(session, url))
tasks.append(task)
results = await asyncio.gather(*tasks)
return results
async def main():
urls = [
'https://www.python.org',
'https://www.google.com',
'https://www.baidu.com',
]
results = await fetch_all(urls)
for result in results:
print(result)
if __name__ == '__main__':
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
In this code, we first define a function called fetch
which takes a ClientSession
object and a URL and returns the text content of the response. The fetch_all
function takes a list of URLs and uses asyncio.gather
to execute multiple fetch
calls concurrently. Finally, we define a main function that creates a list of URLs and calls the fetch_all
function to retrieve their contents.
When we run this code, we see that it fetches the contents of all three URLs concurrently:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" ...
<!doctype html>
<html itemscope="" itemtype="http://schema.org/WebPage" lang="en">
<head> ...
<!DOCTYPE html>
<html lang="zh-CN">
<head>
...
Asynchronous programming can be a powerful tool for improving the performance and responsiveness of your programs. By allowing tasks to be executed in a non-blocking way, you can make your programs more efficient and more user-friendly.