First on the understanding of the code:
1 #Coding:utf-82 defconsumer ():3C_r ="'4 while1:5m =yieldC_r6 if notm:7 return8 Print("Consumer {}". Format (m))9C_r ='OK'Ten defProduce (c): Onen =0 A Next (c) - whileN<5: -N+=1 the Print("Produce {}". Format (n)) -P_r =c.send (n) - Print("consumer return {}". Format (p_r)) - c.close () +c =consumer () -Produce (c)
1. Next (c) Start the generator (by the way, next (c) is equivalent to C.send (None)).
2. When encountering C.send (None) in the produce, the consumer code is executed, and when it encounters yield in consumer, it jumps to produce to execute, and the C_r value is given p_r.
3. In the loop, the next time C.send (n) is encountered, the code to execute consumer is skipped, and the value of n is taken to give M.
4. The essence of this is to jump between two tasks through the two key points of c.send () and yield, and to piggyback on some information.
Understanding of yield creation co-process