您的位置:首页 > 编程语言 > Python开发

使用python的yield实现任务调度.给定一个任务列表,每个任务轮流切换执行,类似于切片

2016-07-14 15:00 941 查看
任务:

给定一个数N, 每次对这个数减1

给定一个数N, 每次对这个数加的次数统计

任务列表就是上面多个任务, 要求每个任务轮流执行(调度):

#!/bin/python3.5
#coding=utf8

'''
sched task yield
'''

def count_donw(n):
while n > 0:
print("count donw", n)
yield
n -= 1

def count_up(n):
x = 0
while x < n:
print ("up times:", x)
yield
x += 1

from collections import deque

class SchedTask():

def __init__(self):
self.dq = deque()

def add_task(self, task):
self.dq.append(task)

def run(self):
while True:
task = self.dq.popleft()
try:
next(task)
self.dq.append(task)
except StopIteration:
pass

if __name__ == "__main__":
sched = SchedTask()
sched.add_task(count_donw(6))
sched.add_task(count_donw(3))
sched.add_task(count_up(10))
sched.run()

打印结果:
count donw 6

count donw 3

up times: 0      

count donw 5

count donw 2

up times: 1

count donw 4

count donw 1

up times: 2

count donw 3

up times: 3

count donw 2

up times: 4

count donw 1

up times: 5

up times: 6

up times: 7

up times: 8

up times: 9
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: