银行家算法

银行家算法是一种用于防止系统死锁的资源分配策略。它通过在分配资源前检查安全性来确保系统不会进入不安全状态。在类比中,这个算法就像是一个闯关游戏,只有当进程的资源需求小于系统可用资源时,才会进行分配。如果所有进程都能按顺序获取所需资源并完成,那么系统处于安全状态。算法的关键步骤包括资源需求分析和安全性检查。
摘要由CSDN通过智能技术生成

银行家算法

银行家算法主要用于避免死锁。原理是进行资源分配之前先计算资源分配的安全性,分配不会导致系统进入不安全状态,则将资源分配给进程。否则让进程等待。注意该算法的核心是安全性的判断:可以理解成一个闯关游戏,若主角的攻击力、防御力、(剩余资源数量)全部都高于某个敌人对应的攻击力、防御力(对应的请求资源的数量), 则主角可以打败这个怪兽并全部获取怪兽的属性(分配和回收资源),若主角可以在这个规则下打败全部的怪兽,则这样的情况下是安全状态。

下图为本算法的基本流程图:
在这里插入图片描述

/*
Banker's Algorithm
2019-11-10
input data format:
====================
process_number	source_number
s1_avl s2_avl s3_avl...
p1_s1_max	p1_s2_max	p1_s3_max...	p1_s1_alc	p1_s2_alc	p1_s3_alc...
p2_s1_max	p2_s2_max	p2_s3_max...	p2_s1_alc	p2_s2_alc	p2_s3_alc...
p3_s1_max	p3_s2_max	p3_s3_max...	p3_s1_alc	p3_s2_alc	p3_s3_alc...
...
process_id  s1_req		s2_req		s3_req...
...
====================
*/

#include<stdio.h>
#include<string.h>
#include<vector>
#include<string>
#include<iostream>
using namespace std;
typedef vector<int> array;
typedef vector<int> arrays[100];

array Available, Finish, Request;
arrays Max, Allocation, Need;
int ProNum, SoureNum;	//process number and source number;
int Running;	//the munber of process that still running
int Pid;		//the id of process that request source

void testPrintf();
int getData();
void initNeed();
void updateNeed();
void initData();
int safetyCheck();
void getRequest();
int Satifycheck();
bool IsSatisfy();

int main(){
   
	//get input data and printf if input accepted
	if (getData() == 0){
   
		printf("Get data success: \n");
		testPrintf();
	}
	else{
   
		printf("Get data fail, exit!");
		return 0;
	}
	//check if safe before recevie a requestment
	printf("First check: ");
	if (safetyCheck() < 0){
   
		printf("The system is unsafe!\n");
		return 0;
	}
	else{
   
		printf("The system is safe, begin to receive requestment! \n\n");
	}
	//receive request of process and handle it
	Running = ProNum;	
	while (Running != 0){
   
		getRequest();
		//check if owned source is enough to give to the process
		if (!IsSatisfy()){
   
			printf("Source not enough, It process need to block!\n");
			testPrintf();
			continue;
		}
		//give those source to process
		for (int i 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值