设计一个任务调度与执行工具。
要求:
1. 任务有输入输出和状态。并且支持内容自由扩展。(扩展任务执行内容,不包括扩展输入输出。)。
2. 任务包括依赖关系,一个任务可以依赖另一个(只能是1个或0个)任务的输出作为自己的输入。并且任务按照依赖的顺序执行。
3. 当一个任务的状态改变时,能自动一次执行依赖他的任务。依赖他的任务需要重新执行。
// V1
#include "stdafx.h"
#include <iostream>
#include <vector>
#include <list>
#include <stack>
using namespace std;
typedef struct
{
// ... ...
// 定义任务的状态
// ... ...
}Status;
class Task{
int taskNum; //任务数目
list<int> *adjacents; //邻接矩阵,任务间的依赖关系
vector<Status> status; //记录每个任务的状态
public:
Task(int _tasknum){
taskNum = _tasknum;
adjacents = new list<int>[taskNum];
status.resize(taskNum);
}
void changeStatus(int t, Status s);
void addAdjacent(int t1, int t2);
};
/*
* 改变第t个任务的状态,与之关联的任务状态均改变
*/
void Task::changeStatus(int t, Status s){
list<int>::iterator iter;
status[t] = s;
for (iter = adjacents[t].begin(); iter != adjacents[t].end(); iter++){
changeStatus(*iter, s);
}
}
/*
* 添加任务间的依赖,t2依赖于t1
*/
void Task::addAdjacent(int t1, int t2) {
adjacents[t1].push_back(t2);
}
// V2
#include "stdafx.h"
#include <iostream>
#include <vector>
#include <list>
#include <stack>
using namespace std;
typedef struct
{
// ... ...
// 定义任务的状态(自定义)
// ... ...
}Status;
class Task{
int taskNum; //任务数目
int taskIndex; //记录被改变状态的任务
list<int> *adjacents; //邻接矩阵,记录任务间的依赖关系
vector<Status> status; //记录每个任务的状态
public:
Task(int _tasknum){
taskNum = _tasknum;
taskIndex = -1;
adjacents = new list<int>[taskNum];
status.resize(taskNum);
}
void addAdjacent(int t1, int t2);
void changeStatus(int t, Status s);
void statusRefresh(int t, Status s);
};
/*
* 添加任务间的依赖关系,t2依赖于t1
*/
void Task::addAdjacent(int t1, int t2) {
adjacents[t1].push_back(t2);
}
/*
* 改变第t个任务的状态,与之关联的任务状态均改变
*/
void Task::changeStatus(int t, Status s){
taskIndex = t;
status[t] = s;
statusRefresh(t, s);
}
/*
* 递归,改变与t依赖的任务的状态
*/
void Task::statusRefresh(int t, Status s){
list<int>::iterator iter;
for (iter = adjacents[t].begin(); iter != adjacents[t].end(); iter++){
if(taskIndex == *iter) // 根据题意,任务间的依赖关系可以出现环状,这里做一下判断,
break; // 在有环的情况下,当回到初始点时,结束更新并跳出。
status[*iter] = s; // 这里“改变状态”是直接用新状态覆盖老状态。
statusRefresh(*iter, s);
}
}