asyncio is the standard library introduced in Python version 3.4, which has direct built-in support for asynchronous IO. asyncio's Programming model is a message loop. Today we will discuss in detail the coroutine and Future objects in asyncio
">The relationship between coroutine and FutureIt seems that both are the same, because the following syntax can be used to obtain results asynchronously,result = await future result = await coroutine
generatorfunction, which can be received from the outside Parameters can also produce results. The advantage of using coroutine is that we can pause a function and then resume execution later, for example, when network operations are involved, the function can be stopped until the response arrives. During the time, we can switch to other tasks to continue execution.
And Future is more like a Promise object inJavascript It is a placeholder whose value will be calculated in the future. . In the above example, when we are waiting for the network IO function to complete, the function will give us a container, and the Promise will fill the container when it is completed. After filling, we can use the Callback function to obtain it. Actual results.
Task object is a subclass of Future, which links coroutine and Future, and encapsulates coroutine into a Future object. Generally, you will see two methods of starting tasks.tasks = asyncio.gather( asyncio.ensure_future(func1()), asyncio.ensure_future(func2()) ) loop.run_until_complete(tasks)
tasks = [ asyncio.ensure_future(func1()), asyncio.ensure_future(func2()) ] loop.run_until_complete(asyncio.wait(tasks))
BaseEventLoop.run_until_complete(future) Run until the Future is done. If the argument is a coroutine object, it is wrapped by ensure_future(). Return the Future's result, or raise its exception.
exit way of the Task task
is in the task loop of asyncio , if you use CTRL-C to exit, even if the exception is caught, the task in the Event Loop will report an error, and the following error will appear, Task was destroyed but it is pending!task:
for=
for task in asyncio.Task.all_tasks(): task.cancel()
try: loop.run_until_complete(tasks) except KeyboardInterrupt as e: for task in asyncio.Task.all_tasks(): task.cancel() loop.run_forever() # restart loop finally: loop.close()
The above is the detailed content of Detailed explanation of how to use coroutine objects and Future objects in asyncio. For more information, please follow other related articles on the PHP Chinese website!