1. Comparison between coroutines and threads and their applicable scenarios
1 Shared variable problem
Multiple threads may compete for variables in multiple threads, so the variable needs to be locked; there is only one thread at any time in the coroutine, so the variable does not need to be locked.
However, although coroutines do not compete for variables like multi-threads, they still share variables like multi-threads, that is, the common variable will also change when it changes at some point and references at another place.
2 Applicable scenarios for coroutines
From a resource perspective, a coroutine has only one thread and can only use one CPU core, so it is suitable for IO-intensive (including disk IO and network IO) functions, and is not suitable for computationally intensive functions.
From the repetition of things, coroutines are similar to multithreading, suitable for functions (for or while) that are repeatedly called, and can also be used for multiple functions that do different things.
3 Coroutine switch
Threads are controlled and switched by the operating system and do not need to be scheduled by ourselves; however, coroutines are manifested as threads in the operating system, and the scheduling operating system is powerless and we have to implement them ourselves.
The await keyword indicates that when the location is blocked, the CPU can be executed, that is, switch to the next coroutine to run; but to the end, it seems that only await () is available (there is also future, but this is not considered for now).
Therefore, each coroutine must use await () to give to other coroutines somewhere (especially within the loop). Otherwise, if the coroutines have not given up, then other coroutines can only wait until the coroutines are completed before they can run.
2. Coroutine code implementation
1 Definition of coroutine function
Write whatever normal functions are written, and add async to the def. like:
async def say_after(delay, what): await (delay) print(what)
2 Calling of coroutine functions
The entry function is called using (). like:
import asyncio async def main(): print(f"started at {('%X')}") print('hello world!') print(f"finished at {('%X')}") if __name__ == "__main__": # The entry function is called through () (main())
Generally, when calling coroutine function, add the await keyword before it to call:
import asyncio import time async def say_after(delay, what): await (delay) print(what) async def main(): print(f"started at {('%X')}") # Add await in front to call # This form is no different from the normal synchronous execution program effect, it is still necessary to execute the next step after the previous step. await say_after(1, 'hello') await say_after(2, 'world') print(f"finished at {('%X')}") if __name__ == "__main__": # The entry function is called through () (main())
The last one is throughasyncio.create_task()
Call general coroutine functions.
The second way of calling is to call general coroutine functions, but if you just call this, the coroutine function does not work. For example, the above function still takes 3 seconds like the normal synchronous version.
The meaning of coroutines isasyncio.create_task()
Call form,asyncio.create_task()
Coroutine functions can be wrapped into tasks, and multiple tasks can be executed in parallel. The following writing method only takes time2Second。
import asyncio import time #No one answers the questions encountered during study? The editor has created a Python learning exchange group: 153708845class TestAsync: async def say_after(self,delay, what): await (delay) print(what) async def main(self): print(f"started at {('%X')}") task_list = [] # is equivalent to [1,2] for i in range(1, 3, 1): # Step 1: Use asyncio.create_task() to call the coroutine function and encapsulate it into a task tmp_task = asyncio.create_task(self.say_after(i, 'hello')) task_list.append(tmp_task) # Step 2, await task for tmp_task in task_list: await tmp_task print(f"finished at {('%X')}") if __name__ == "__main__": obj = TestAsync() (())
This is the end of this article about coroutines in Python. For more related content on coroutines in Python, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!