First, coroutine
1. historical process:
(1) introduction of 3.4 coroutine, with the yield to achieve
(2) introducing coroutine 3.5 Syntax
(3) to achieve relatively good coroutine package has asyncio, tornado, gevent
2. Definitions: coroutine is a computer program component to produce a non-preemptive multitasking subroutine, coroutine allowing different entry points or at different locations suspended program execution is started
3. From a technical perspective, coroutine is a pause function can be performed, or simply the coroutine understood as a generator
4. coroutine resource consumption is very small, smaller than the multi-process consumes more resources, so multi-concurrent coroutines save more resources.
The realization coroutine
(1) yield return; (2) send call
(3) coroutine three states:
inspect.geigeneratorstate (...) determined function, the function returns one of the following string:
GEN_CREATED: waiting to start execution
GEN_RUNNING: interpreter executing
GEN_SUSPENED: pause the expression yield
GEN_CLOSED: execution ends
next Wolff ( prime)
Example 6. sub (note inside Notes)
DEF simple_coroutine (): Print ( " -> Start " ) the X- = yield # This function performs here stopped, waiting assigned to it, which is behind the send statement Print ( " -> recived " , the X-) # main thread SC = simple_coroutine () Print (1111 ) # can be used sc.send (None), the same effect Next (SC) # Wolff Print (2222 ) sc.send ( " zhexiao " )
Execution order as follows:
Results of the:
7, both the return value and send a statement to code
note:
The yield can be seen through the back of the return statement is equivalent to send, then equivalent to the input sentence
DEF simple_coroutine2 (A): Print ( " -> Start " ) B = yield A # can be seen by the yield corresponds to the back of the return statement send, then equivalent to the input sentence Print ( " -> recived " , A, B ) C = the yield A + B Print ( " -> recived " , A, B, C) SC2 = simple_coroutine2 (. 5 ) AA = Next (SC2) Print (AA) BB = sc2.send (. 6) # 5,6 Print (bb) cc = sc2.send(7) #5,6,7 print(cc)
8. The abnormality coroutine
Coroutine unhandled exception will bubble up, passed to the next function or send method of the caller (i.e., triggering object coroutine)
A method of stopping coroutine: transmitting a sentinel value, so coroutine exits built None constants and the like are often used as Ellipsis sentinel value
Second, the source
d27_3_usage_of_coroutine.py
https://github.com/ruigege66/Python_learning/blob/master/d27_3_usage_of_coroutine.py
2.CSDN: https: //blog.csdn.net/weixin_44630050 (Xi Jun Jun Moods do not know - Rui)
3. Park blog: https: //www.cnblogs.com/ruigege0000/
4. Welcomes the focus on micro-channel public number: Fourier transform public personal number, only for learning exchanges, backstage reply "gifts" to get big data learning materials