DYBOY's Blog

[Python]协程

Python对协程的支持是通过generator实现的。

generator中,我们不但可以通过for循环来迭代,还可以不断调用next()函数获取由yield语句返回的下一个值。

但是Pythonyield不但可以返回一个值,它还可以接收调用者发出的参数。

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)

输出:

D:\APP\python36\python3.exe C:/Users/stdy/Desktop/test.py
[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

Process finished with exit code 0
版权声明:《 [Python]协程 》为DYBOY原创文章未经允许不得转载。

 DYBOY
 作者签名:安全从业者,爱好安全产品开发,渗透测试,Web漏洞研究

发表评论:

用心评论~

TOP
Powered by Emlog | Theme:Monkey by DYBOY
渝ICP备16008772号
sitemap