Part of the asynchronous framework
- Asynchronous non-blocking, asyncio
- Tornado, FastAPI, Django3. x ASGI, AIOHTTP are all asynchronizing –> improving performance
Coroutines,
- Coroutines are not provided by computers that programmers think are created.
- A Coroutine, also known as a tasklet, is a user-state context switching technology.
- In a nutshell: it’s a thread that switches blocks of code between each other.
- Def fun1(): def fun1(): def fun1(): Print (1) print(2) def fun2() def fun2() print(2) def fun2() Print (3) print(4) print(core) # print(core) # print(core) # print(core) # 1234 123456789101112131415
There are several ways to implement coroutines in Python:
- Greenlet is a third-party module and an early one
- The yield keyword implementation
- Asyncio decorator (Py3.4 and above)
- Async, await keywords (py3.5 + [recommended])
Implement coroutines through greenlets
PIP install greenlet - https://pypi.doubanio.com/simple - I installed modules from greenlet import greenlet - import module def fun1 () : Print (1) Print (2) print(2) gr2.switch() print(2) gr2.switch() def fun2() Print (4) print(8) gr1 = greenlet(fun1) gr2 = Greenlet (fun2) gr1.switch() -- Step 1: Execute func1. The func1 function outputs 1, 3, 2, 4. Coroutines 123456789101112131415161718192021222324252627Copy the code
Implement coroutines with the yield keyword
def fun1(): Yield 1 yield from fun2() -- when func2 () is called, fuc2 () will be executed down yield 2 -- when func2 () is executed, it will jump back to the position where it just escaped, and continue to execute fuc1 def fun2(): F1 = fun1() or # f = fun1() for item in f1: Print (item) # print(next(f)) # print(next(f)) # print(next(f) # this way was a fake coroutines, don't recommend use, but also realize the definition of coroutines. 12345678910111213141516171819Copy the code
Implemented via asyncio module (Python after 3.4)
Import asyncio.coroutine def fun1(): import asyncio.coroutine def fun1(): Print (1) @asyncio.coroutine def fun2(): print(2) @asyncio.coroutine def fun2() Print (4) tasks = [asyncio.ensure_future(fun1())), [loop = asyncio.get_event_loop() loop.run_until_complete(fun1())) # Notice I/O block Automatic switch (python3.5 recommended keywords) after 12345678910111213141516171819202122Copy the code
Async & await keyword implementation coroutines (after Python3.5)
Import asyncio async def fun1(): print(1) await asyncio.sleep(2) print(2) async def fun2(): Print (4) tasks = [asyncio.ensure_future(fun1())), Asyncio.ensure_future (fun2())] loop = asyncio.get_event_loop() loop.run_until_complete(fun1()) #Copy the code
PS: If you need Python learning materials, please click on the link below to obtain them
The full code can be obtained by clicking on the link below
[Python free Learning materials and group communication solutions to join](https://jq.qq.com/?_wv=1027&k=rwkJ1Qtr)