使用DFS(深度优先搜索)遍历求出所有的安全序列。
数据结构
先上头文件说明,实现此算法用到的数据结构和命名。
#ifndef _DATA_STRUCTURE
#define _DATA_STRUCTURE
// 表示资源个数
#define M (4)
// 表示进程个数
#define N (4)
// 当前状态还剩多少可用的资源
struct AvailableD;
// 每个进程对每个资源的最大需求量
struct MaxD;
// 当前分配个每个进程的资源数目
struct AllocationD;
// 每个进程还需要多少资源数目(最大需求 - 当前分配)
struct NeedD;
// 当前状态每个进程请求的资源数量
struct RequestD;
// 存放安全序列的数据结构(名字叫 Queue 实际上是栈的实现【FILO先进后出】)
struct QueueD;
// 表明每个进程是否在安全序列中
struct StatusD;
typedef struct AvailableD *Available;
typedef struct MaxD *Max;
typedef struct AllocationD *Allocation;
typedef struct NeedD *Need;
typedef struct RequestD *Request;
typedef struct QueueD *Queue;
typedef struct StatusD *Status;
Available create_available();
Allocation create_allocation();
Max create_max();
Need create_need();
Queue create_queue();
int queue_full(Queue queue);
int queue_empty(Queue queue);
void queue_add(Queue queue, int data);
int queue_get(Queue queue);
void queue_display(Queue queue);
Status create_status();
void display_need(Need need);
/* 更新 need 数组 */
void update_need(Need need, Allocation allocation, Max max);
/* 将 allocation 矩阵的 第 row 行的值加(减)到 available 里 */
void update_available(Allocation allocation, int row, Available available, int is_add);
/* 检查 available 是否满足 need 的第 row 行的需求 */
void check_available(Allocation allocation, Need need, Available available, int row, Queue queue, Status status);
#endif
算法步骤
首先检查当前剩余的资源数目是否满足某个进程的需求量,也就是说判断 Available 向量中每一个资源数目是否大于等于 Need 矩阵中某一个进程的需求量;
如果对于进程 row ,对每个资源数目的需求量小于当前可用的系统资源;首先检查当前进程是否已经在安全序列中,若存在就判断下一个进程;
若当前进程 row 还没有处在安全序列,就开始深度优先搜索:将当前进程 row 已经分配到的系统资源数目加到当前可用的资源数目中,即 Allocation 矩阵中第 row 行的所有数目加到 Available 向量中;然后将当前进程 row 添加到安全序列中(此安全序列是一个栈);递归调用搜索的函数,向下一个进程开始搜索;
在搜索的过程中需要判断所有的进程是否已经添加到安全序列中,即查看安全序列(栈)的大小是否等于当前系统的进程数目;若达到了就将安全序列输出并且开始回溯;此判断应该放在深度优先搜索函数的前面,用来作为递归出口;
然后将最近加入到安全序列中的进程从安全队列中删除,即从栈中弹出一个元素,记为 row;然后修改此进程row未加在安全序列中的状态;将此进程row收回的资源数目归还,即从 Available 向量中减去 Allocation 矩阵中第 row 行的数目;然后向下一个进程搜索。
核心代码
/**
* allocation: Allocation 每个进程已经分配的资源数目的矩阵
* need: Need 每个进程还需的资源数目的矩阵
* available: Available 剩余资源数的矩阵
* row: 表示从哪个进程开始向下扫描
* queue: 已加入安全序列的进程(栈性质)
* status: 表示每个进程是否已经存在于安全序列
* */
void check_available(Allocation allocation, Need need, Available available, int row, Queue queue, Status status)
{
int temp = row;
int i;
int flag = 1;
// 递归出口
if (queue->length == 4)
{
printf("Safe sequence: ");
queue_display(queue);
return;
}
do
{
for (i = 0; i < M; i++)
{
if (available->vector[i] < need->matrix[row][i])
{
flag = 0;
break;
}
}
if (flag)
{
if (status->vector[row] == 1)
{
row = (row + 1) % N;
continue;
}
// 深搜准备
update_available(allocation, row, available, 1);
queue_add(queue, row);
status->vector[row