Python basic grammar 27-coroutine asynchronous I/O

Asynchronous IO: It is to initiate an IO operation (such as: network request, file reading and writing, etc.). These operations are generally time-consuming. You don’t need to wait for it to end, you can continue to do other things, and a notification will be sent when it ends.
Coroutine: Also known as micro-thread, it is executed in one thread and can be interrupted at any time when executing the function. It is controlled by the program (user) itself, and the execution efficiency is extremely high. Compared with multi-thread, there is no overhead of switching threads and multi-thread lock mechanism .
Asynchronous IO operations in python are implemented through asyncio.
1. Coroutine The coroutine
is similar to the generator, and both contain the yield keyword. The difference is that the yield keyword in the coroutine usually appears on the right side of =, and can produce a value a (y = yield a) or not. Value is None (y = yield). The caller can use the send function to send values ​​to the coroutine.
Pause at yield when activating the coroutine, wait for the caller to send data, and continue to pause at yield next time. Fundamentally, yield is a tool for process control, which can realize cooperative multitasking, which is also the basis for explaining asynchronous IO later.
Example of a coroutine:
def demo(name):
    print('The name of the coroutine to start:',name)
    x = yield name#When calling next(), it will pause after yielding the value to the right of yield; when calling send(), it will yield Assign the output value to x, and run it down
    print('the value sent:',x)
c = demo('jack')
print('the return value of next:',next(c))
print('the return sent Value: ', c.send(6))
results such as

Guess you like

Origin blog.csdn.net/a316495442/article/details/128485688