Coroutine: compile a function as a task that can process input parameters using the yield statement and create coroutine in the form of the expression yield: compile the function as a task that can process input parameters
Use the yield statement and create a coroutine in the form of the expression yield
# Matching case:
def print_info(data): print('Looking for',data); while True: line = (yield) if data in line: print(line);
The above function is a coroutine program. to use this function, you first need to call it and execute it to the first yield statement.
Info = print_info ('Python'); info. _ next _ (); # run the first yield statement forward.
Output result:
Looking for python
Then, use the send method to send data to the coprocessor for processing.
info.send('Hell world'); info.send('this is python'); info.send('python goods');
If the sent data contains the data parameter value, the data is returned if the match is successful.
Output result:
Looking for python
This is python
Python goods
When send () is the sent value of the coroutine, the program is in the SUSPEND state. after the sent value, the yield expression returns this value, the subsequent program processes the return value until the next expression ends. this process continues until the coroutine function returns or calls the close method.
Data generated based on some programs will be used by another part of the program (producer-user mode)
When writing a concurrent program, the coroutine function is obvious. it represents a user of data.
info =[ print_info('python'), print_info('hello'), print_info('chunrui') ]
Call _ next _ () to prepare all the matching objects.
for n in info: n.__next__();
Define a function to obtain data in each column in the file and pass it to the generator.
Def tail (f): for line in f: if not line: time. sleep (0.1); continue; # if it does not exist, the next yield line will be postponed by 0.1 s; myList = tail (open ('E:/work.txt '))
Loop the values in myList and send them to the coroutine program.
for m in myList: for n in info: n.send(m);
Output result:
Looking for pythonLooking for helloLooking for chunruipython is conputer languagechunrui is namehello world is the first caseI like to use pythonmy name is chunrui
Summary:
1. coroutine: when the coroutine is paused, you can obtain the return value from the task function that can process the input parameters. when the call is returned to the program, additional or new parameters can still be passed in from the last exit.
2. use the send function to send parameters for the coroutine.
The above is the content of the coroutine (coprocessor) in python. For more information, see PHP Chinese network (www.php1.cn )!