yield的实现
python2.7或者python3可执行
def consumer():
r = ''
while True:
n = yield r
if not n:
return
print('[CONSUMER] Consuming %s...' % n)
r = '200 OK'
def produce(c):
c.send(None)
n = 0
while n < 5:
n = n + 1
print('[PRODUCER] Producing %s...' % n)
r = c.send(n)
print('[PRODUCER] Consumer return: %s' % r)
c.close()
c = consumer()
produce(c)
[PRODUCER] Producing 1...
[CONSUMER] Consuming 1...
[PRODUCER] Consumer return: 200 OK
[PRODUCER] Producing 2...
[CONSUMER] Consuming 2...
[PRODUCER] Consumer return: 200 OK
[PRODUCER] Producing 3...
[CONSUMER] Consuming 3...
[PRODUCER] Consumer return: 200 OK
[PRODUCER] Producing 4...
[CONSUMER] Consuming 4...
[PRODUCER] Consumer return: 200 OK
[PRODUCER] Producing 5...
[CONSUMER] Consuming 5...
[PRODUCER] Consumer return: 200 OK
注意到consumer函数是一个generator,把一个consumer传入produce后:
1. 首先调用c.send(None)启动生成器;
2. 然后,一旦生产了东西,通过c.send(n)切换到consumer执行;
3. consumer通过yield拿到消息,处理,又通过yield把结果传回;
4. produce拿到consumer处理的结果,继续生产下一条消息;
5. produce决定不生产了,通过c.close()关闭consumer,整个过程结束。
整个流程无锁,由一个线程执行,produce和consumer协作完成任务,所以称为“协程”,而非线程的抢占式多任务。
最后套用Donald Knuth的一句话总结协程的特点:
“子程序就是协程的一种特例。
Asyncio
python3可执行
事件循环: 在计算系统中,可以产生事件的实体叫做事件源,能处理事件的实体叫做事件处理者。此外,还有一些第三方实体叫做事件循环。它的作用是管理所有的事件,在整个程序运行过程中不断循环执行,追踪事件发生的顺序将它们放到队列中,当主线程空闲的时候,调用相应的事件处理者处理事件。最后,我们可以通过下面的伪代码来理解事件循环
即开启一个循环不断获取事件,只要事件触发就进行woker
while (1) {
events = getEvents();
for (e in events)
processEvent(e);
}
所有的时间都在 while 循环中捕捉,然后经过事件处理者处理。事件处理的部分是系统唯一活跃的部分,当一个事件处理完成,流程继续处理下一个事件。
• loop = get_event_loop(): 得到当前上下文的事件循环。
• loop.call_later(time_delay, callback, argument): 延 后 time_delay 秒 再 执 行
callback 方法。
• loop.call_soon(callback, argument): 尽可能快调用 callback, call_soon() 函数结束,
主线程回到事件循环之后就会马上调用 callback 。
• loop.time(): 以float类型返回当前时间循环的内部时间。
• asyncio.set_event_loop(): 为当前上下文设置事件循环。
• asyncio.new_event_loop(): 根据此策略创建一个新的时间循环并返回。
• loop.run_forever(): 在调用 stop() 之前将一直运行。
import asyncio
import datetime
import time
def function_1(end_time, loop):
print "function_1 called"
if(loop.time() + 1.0 ) < end_time:
loop.call_later(1, function_2, end_time ,loop)
else:
loop.stop()
def function_2(end_time, loop):
print "function_2 called"
if(loop.time() + 1.0 ) < end_time:
loop.call_later(1, function_3, end_time ,loop)
else:
loop.stop()
def function_3(end_time, loop):
print "function_2 called"
if(loop.time() + 1.0 ) < end_time:
loop.call_later(1, function_4, end_time ,loop)
else:
loop.stop()
def function_4(end_time, loop):
print "function_5 called"
if(loop.time() + 1.0 ) < end_time:
loop.call_later(1, function_4, end_time ,loop)
else:
loop.stop()
loop = asyncio.get_event_loop()
end_loop = loop.time() + 9.0
loop.call_soon(function_1, end_loop ,loop)
loop.run_forever()
loop.close()
运行结果如下:
python3 event.py
function_1 called
function_2 called
function_3 called
function_1 called
function_2 called
function_3 called
function_1 called
function_2 called
function_3 called
执行过程:
1. 首先,我们要得到这个事件循环:: loop = asyncio.get_event_loop()
然后我们通过 call_soon 方法调用了 function_1() 函数。 end_loop = loop.time() + 9.0
让我们来看一下 function_1() 的定义:
loop.call_soon(function_1, end_loop, loop)
def function_1(end_time, loop):
print ("function_1 called")
if (loop.time() + 1.0) < end_time:
loop.call_later(1, function_2, end_time, loop)
else:
loop.stop()
这个函数通过以下参数定义了应用的异步行为:
• end_time: 定义了 function_1() 可以运行的最长时间,并通过 call_later 方法传入到
function_2() 中作为参数
• loop: 之前通过 get_event_loop() 方法得到的事件循环
function_1() 的任务非常简单,只是打印出函数名字。当然,里面也可以写非常复杂的操作。
print (“function_1 called”)
任务执行结束之后,它将会比较 loop.time() +1s和设定的运行时间,如果没有超过,使用 call_later在1秒之后执行 function_2() 。 if (loop.time() + 1.0) < end_time:
loop.call_later(1, function_2, end_time, loop)
else:
loop.stop()
function_2() 和 function_3() 的作用类似。
如果运行的时间超过了设定,时间循环终止
利用@asyncio.coroutine 装饰器管理协程
import asyncio
@asyncio.coroutine
def coroutine_function(function_arguments):
# DO_SOMETHING
示例:
# Asyncio Finite State Machine
import asyncio
import time
from random import randint
@asyncio.coroutine
def StartState():
print("Start State called \n")
input_value = randint(0, 1)
time.sleep(1)
if (input_value == 0):
result = yield from State2(input_value)
else:
result = yield from State1(input_value)
print("Resume of the Transition : \nStart State calling " + result)
@asyncio.coroutine
def State1(transition_value):
outputValue = str("State 1 with transition value = %s \n" % transition_value)
input_value = randint(0, 1)
time.sleep(1)
print("...Evaluating...")
if input_value == 0:
result = yield from State3(input_value)
else :
result = yield from State2(input_value)
result = "State 1 calling " + result
return outputValue + str(result)
@asyncio.coroutine
def State2(transition_value):
outputValue = str("State 2 with transition value = %s \n" % transition_value)
input_value = randint(0, 1)
time.sleep(1)
print("...Evaluating...")
if (input_value == 0):
result = yield from State1(input_value)
else :
result = yield from State3(input_value)
result = "State 2 calling " + result
return outputValue + str(result)
@asyncio.coroutine
def State3(transition_value):
outputValue = str("State 3 with transition value = %s \n" % transition_value)
input_value = randint(0, 1)
time.sleep(1)
print("...Evaluating...")
if (input_value == 0):
result = yield from State1(input_value)
else :
result = yield from EndState(input_value)
result = "State 3 calling " + result
return outputValue + str(result)
@asyncio.coroutine
def EndState(transition_value):
outputValue = str("End State with transition value = %s \n" % transition_value)
print("...Stop Computation...")
return outputValue
if __name__ == "__main__":
print("Finite State Machine simulation with Asyncio Coroutine")
loop = asyncio.get_event_loop()
loop.run_until_complete(StartState())
运行结果如下:
Finite State Machine simulation with Asyncio Coroutine
Start State called
...Evaluating...
...Evaluating...
...Evaluating...
...Evaluating...
...Evaluating...
...Evaluating...
...Evaluating...
...Evaluating...
...Evaluating...
...Stop Computation...
Resume of the Transition :
Start State calling State 2 with transition value = 0
State 2 calling State 3 with transition value = 1
State 3 calling State 1 with transition value = 0
State 1 calling State 3 with transition value = 0
State 3 calling State 1 with transition value = 0
State 1 calling State 3 with transition value = 0
State 3 calling State 1 with transition value = 0
State 1 calling State 2 with transition value = 1
State 2 calling State 3 with transition value = 1
State 3 calling End State with transition value = 1
每一个状态都由装饰器装饰:
@asyncio.coroutine
例如, S0 的定义如下所示:
@asyncio.coroutine
def StartState():
print("Start State called \n")
input_value = randint(0, 1)
time.sleep(1)
if (input_value == 0):
result = yield from State2(input_value)
else:
result = yield from State1(input_value)
print("Resume of the Transition : \nStart State calling " + result)
通过 random 模块的 randint(0, 1) 函数生成了 input_value 的值,决定了下一个转换状态。此函数随机生成1或0:
input_value = randint(0, 1)
得到 input_value 的值之后,通过 yield from 命令调用下一个协程。
if (input_value == 0):
result = yield from State2(input_value)
else:
result = yield from State1(input_value)
result 是下一个协程返回的string,这样我们在计算的最后就可以重新构造出计算过程。
启动事件循环的代码如下:
if __name__ == "__main__":
print("Finite State Machine simulation with Asyncio Coroutine")
loop = asyncio.get_event_loop()
loop.run_until_complete(StartState())
总结asyncio的流程:
1. 创建事件循环;
2. 编写yeild子模块任务;
3. 开始触发执行;
4. 定义循环结束语句;