Fluent python-advanced article-coroutine asyncio

asyncio

  • Here is mainly to introduce the coroutines in python and sort out some confusions in the study. It has not been verified in the source code yet, but only some of my own opinions are recorded. If there is a discrepancy with your ideas, you can discuss together

confused

  • Before writing, everyone should be aware of the basic concepts of some coroutines.
  • First, let’s take a look at an example: The basic process of this example is to create three tasks and perform concurrent operations, where task is the task, and doing is the simulation time-consuming in the task.
import asyncio

async def doing(name):
    print(f"{name} task doing ...")
    for i in range(100):
        # print(f"{name}-{i} doing ...")
        await asyncio.sleep(0.01)

async def task(name):
    print(f"{name} task start ...")
    await doing(name)
    print(f"{name} task stop ...")

def main():
    loop = asyncio.get_event_loop()
    tasks = [
        loop.create_task(task(name)) for name in range(3)
    ]
    loop.run_until_complete(asyncio.wait(tasks))

if __name__ == "__main__":
    main()
  • result
0 task start ...
0 task doing ...
1 task start ...
1 task doing ...
2 task start ...
2 task doing ...
0 task stop ...
1 task stop ...
2 task stop ...
  • In many examples on the Internet, asyncio.sleep(1) is used to simulate time-consuming tasks in tasks. It seems that no one has actually written time-consuming tasks by themselves. The document also emphasizes that asyncio.sleep(1) is a coroutine. , So according to my understanding, the function of await should be to suspend the current task, release CPU resources, and give up resources to other tasks. The default result should be
0 task start ...
1 task start ...
2 task start ...
···
  • But the result is not the imaginary result, which means that await just suspends the current task and executes the content of doing. After that, I did an experiment and canceled == print(f"{name}-{i} doing …" ) == comment, the result is:
···
0-57 doing ...
1-57 doing ...
2-57 doing ...
0-58 doing ...
1-58 doing ...
2-58 doing ...
···
  • This result indicates that the three tasks are concurrently doing an experiment. Set == await asyncio.sleep(0.01) == comment in doing and set the loop to 3, and the result is
0 task doing ...
0-0 doing ...
0-1 doing ...
0-2 doing ...
0 task stop ...
1 task start ...
1 task doing ...
1-0 doing ...
1-1 doing ...
1-2 doing ...
1 task stop ...
2 task start ...
2 task doing ...
2-0 doing ...
2-1 doing ...
2-2 doing ...
2 task stop ...

We found that it has completely become a synchronous method, and then we introduce the following problems

1. What exactly is asyncio.sleep(1)

  • First of all, sleep is indeed a coroutine. I know from other blogs that it is a timer inside. It is an == asynchronous function == instead of a synchronous function to simulate asynchronous time-consuming tasks. Why can't the coroutine we write ourselves do? To achieve this function, because our doing is still a synchronous code, asynchronous operations cannot be achieved, just like if we use asynchronous crawlers, as follows, in fact, after we see the results, we should still be synchronous, because requests is a synchronous library and does not support asynchronous operations. You can use aiohttp to achieve true asynchronous operation. Now we just look at the essence from the phenomenon. After I study the source code, I will analyze whether our vision is really correct.
# 将doing 换成
async def call_on():
    status = requests.get('https://www.baidu.com')
    return status

2. What is the role of await

  • Suspend the current coroutine

Guess you like

Origin blog.csdn.net/DALAOS/article/details/114843400