Python coroutine:
Coroutine, also called micro-threads, shred. . Coroutine English words explain what is coroutines: coroutine is a user-lightweight thread state.
Coroutine has its own stack and register context. When coroutine scheduled handover, the context save registers and stack to another location, the cut back,
Restore previously saved register context and stacks. Thus: coroutine can be left as the last call (i.e., a particular combination of all of the local state)
During each reentrant, the equivalent of a state into the call. Stated another way, when the location of a logic flow exits into the
Coroutine benefits:
-
No need to thread context switching overhead
- No need to start atomic operations lock and synchronization
- Facilitate the switch control flow, simplified programming model
- High concurrency + scalability + low cost: a CPU million for the support coroutine is not a problem, all very suitable for high concurrent processing
Coroutine disadvantages:
- Can not take advantage of multi-core CUP,
- Be blocked (Blocking) The operation would block a whole program
1.1 yield coroutine:
import time import queue def consumer(name): print('--------------start------------') while True: new_baozi = yield print('%s is eating baozi %s' %(name,new_baozi)) time.sleep(1) def producer(): r = con.__next__() #也可以是Next(con) r = con2.__next__() n =0 while n < 5: n += 1 con.send(n) con2.send(n) print("\033[32;1m[producer]\033[0m is making baozi %s" % n) if __name__ == "__main__": con = consumer('c1') con2 = consumer('c2') p = producer()