首页 > 代码库 > Asyncio中的Task管理
Asyncio中的Task管理
#!/usr/bin/env python# -*- coding: utf-8 -*-import asyncioimport datetimeimport timefrom random import randint@asyncio.coroutinedef 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.coroutinedef 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.coroutinedef 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管理
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。