使用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
给定一个数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
相关文章推荐
- python 利用openpyxl包处理excel数据并作图
- python 进程通信
- Python实现mapreduce程序
- python 学习(四)基础语法
- Python+lxml解析html
- python md5计算
- 为python virtualenv安装exe依赖
- python学习——调试
- python文件批量改名
- python类的简单介绍
- python学习——错误处理
- python 进阶
- python 版本控制及django,git的使用
- 【python问题解决】RuntimeError:NLPIR function 'NLPIR_Init' failed
- python 装饰器
- python中的类简单讲解
- python之各类错误汇总[一]
- python 学习(三)基础语法
- python多线程与同步1
- Python中的str与unicode处理方法