程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

A First Look at Python Asyncio: Basic Concepts and Patterns

編輯:Python

Asynchronous IO (async IO) is an asynchronous programming design and is supported in Python's asyncio module and canUse the two definition keywords async/await to define coroutines, and pass asyncioProvides the foundation and API for running and managing coroutines.


Subroutines and coroutines

In general, most programming languages ​​have methods that follow a so-called "subroutine" calling model.In this model, each call to a function is called execution, moves to the beginning of the function, and continues until the end of the function (or return statement) is reached, at which point execution moves immediately toThe point after the function is called, any subsequent calls to that function are independent, and that call will start again at the beginning.


However, there is an alternative code execution model called the coroutine invocation model.In this calling model, the method (called a coroutine ) that will execute back to the caller has a new method: instead of returning it can "yield" control.When a coroutine's "yields" execution moves back to the point immediately after being called, but future calls to the coroutine don't start again at the beginning, instead they continue from the most recently stopped execution.


This way control can be executed back and forth between the calling code and the coroutine code, as shown below:



Hello program for ayncio


import asyncioimport timeasync def main(): print(f'{time.ctime()} Hello!') await asyncio.sleep(1.0) print(f'{time.ctime()} See you again!')asyncio.run(main())


Run result:

$ python asynciodemo.py Sat Jul 9 23:19:40 2022 Hello!Sat Jul 9 23:19:41 2022 See you again!


asyncio provides a run() function to execute the async def function and then all other coroutines called from there like sleep() function in the code>main() function.



Reference link:

  • Async IO in Python: A Complete Walkthrough


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved