Coroutine, also known as micro thread, fiber. The English name is Coroutine.
Coroutine is another way of multitasking in python, but it occupies a smaller execution unit (understood as a required resource) than a thread. Why it is an execution unit, because it comes with a CPU context. In this way, as long as the right time, we can switch from one coroutine to another. As long as the CPU context is saved or restored during this process, the program can still run.
Popular understanding: In a function in a thread, you can save some temporary variables and other information of the current function anywhere, and then switch to another function for execution. Note that it is not done by calling the function and is switched The number of times and when to switch to the original function are determined by the developer himself
When implementing multitasking, thread switching is far more than just saving and restoring CPU context from the system level. For the efficiency of program operation, the operating system has its own cache and other data for each thread, and the operating system will also help you to restore these data. So thread switching is very performance intensive. But the switching of the coroutine is only the context of operating the CPU, so the system is resistant to switching millions of times a second.
import time
def task1():while True:print("--1--")
time.sleep(0.1)yield
def task2():while True:print("--2--")
time.sleep(0.1)yield
def main():
t1 =task1()
t2 =task2()while True:next(t1)next(t2)if __name__ =='__main__':main()"""
--1----2----1----2----1----2----1----2----1----2----1----2----1----2----1----2----1----2----1----2----1--
Omit...."""
Recommended Posts