The implementation of the association is collaborative rather than preemptive, which is the biggest difference from the process thread. In Python, the use of yield and send can make it easy to implement a co-process.
First review the generator.
If a function uses the yield statement, then it is a generator function. When this function is called, it returns an iterator. When the first call to __next__ () occurs, the generator function body begins execution and terminates when the yield expression is encountered.
The yield value statement returns none when using the __next__ () method, and yield value returns V when the Send (V) method is used. In other words, the __next__ () method is equivalent to the Send (None) method
1 defconsumer ()2 whileTrue:3line =yield#Line receives the return value of the yield expression! 4 Print(Line.upper ())5 6 7 defproductor ():8With open ('Text.txt') as file:9 forI, lineinchEnumerate (file):Ten yield Line One Print("{0} lines". Format (i)) A - -c =consumer () theC.__next__()#手动启动生成器,Note that the python3.x is not C.next () - forIinchproductor (): -C.send (i)
Reference: 91 recommendations for improving Python procedures recommendations 66, 67
The "Python" process implements the producer consumer model