Asyncio中的Task管理
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Asyncio中的Task管理相关的知识,希望对你有一定的参考价值。
#!/usr/bin/env python # -*- coding: utf-8 -*- import asyncio import datetime import time from random import randint @asyncio.coroutine def factorial(number): f = 1 for i in range(2, number+1): print("Asyncio.Task: Compute factorial(%s)" % (i)) yield from asyncio.sleep(1) f *= i print("Asyncio.Task - factorial(%s) = %s" %(number, f)) @asyncio.coroutine def fibonacci(number): a, b = 0, 1 for i in range(number): print("Asyncio.Task: Compute fibonacci (%s)" % i) yield from asyncio.sleep(1) a, b = b, a + b print("Asyncio.Task - fibonacci(%s) = %s" % (number, a)) @asyncio.coroutine def binomialCoeff(n, k): result = 1 for i in range(1, k+1): result = result * (n-i+1) / i print("Asyncio.Task: Compute binomialCoeff (%s)" % (i)) yield from asyncio.sleep(1) print("Asyncio.Task - binomialCoeff(%s , %s) = %s" % (n,k,result)) if __name__ == "__main__": tasks = [asyncio.Task(factorial(10)), asyncio.Task(fibonacci(10)), asyncio.Task(binomialCoeff(20, 10))] loop = asyncio.get_event_loop() loop.run_until_complete(asyncio.wait(tasks)) loop.close()
以上是关于Asyncio中的Task管理的主要内容,如果未能解决你的问题,请参考以下文章
在Python中使用Asyncio系统(3-4)Task 和 Future
从 loop.create_task() 引发的 python asyncio 异常