Coroutine: Write the function as a task that can process the input parameters
Use the yield statement and create the coroutine in the form of the expression yield
#Matcher case:
def print_info(data): print('Looking for',data); while True: line = (yield) if data in line: print(line);
The above The function is a coroutine program. To use this function, you first need to call it and execute forward to the first yield statement
info = print_info('python'); info.__next__(); #向前执行第一条yield语句
Output result:
Looking for python
Then use send The method sends data to the coroutine 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 match will successfully return the data
Output result:
Looking for python
this is python
python goods
send() When sending a value to the coroutine, the program is temporarily suspended. After sending the value, the yield expression will return this value. The subsequent program will process the return value until it encounters the next expression to end this The process will continue to run until the coroutine function returns or the close method is called
The data generated based on one part of the program will be used by another part of the program (producer-consumer mode)
When writing concurrent programs, the role of coroutines is obvious He represents a user of data
info =[ print_info('python'), print_info('hello'), print_info('chunrui') ]
Prepare all matchers by calling __next__()
for n in info: n.__next__();
Define a function to obtain each column of data in the file and pass it to the generator
def tail(f): for line in f : if not line: time.sleep(0.1); continue; #如果不存在 则推迟0.1s 进行下一次 yield line; myList = tail(open('E:/work.txt'))
Loop the values in myList and then send to the coroutine program
for m in myList: for n in info: n.send(m);
Output results:
Looking for python Looking for hello Looking for chunrui python is conputer language chunrui is name hello world is the first case I like to use python my name is chunrui
Summary:
1, Coroutine: The coroutine can process the task function of the input parameters. When the coroutine is paused, we get the return value from it. When the call returns to the program, additional or new parameters can be passed in and we can still continue from where we left off
2, use the send function to send parameters to the coroutine
The above is the content of the coroutine (coroutine) in python. For more related content, please pay attention to the PHP Chinese website (www. php.cn)!