操作系统|| 进程死锁与预防的银行家算法模拟

前言

1.在Java环境下编程实现进程死锁预防的银行家算法模拟,以便更好的理解此进程死锁解决方案。

银行家算法是一种最有代表性的避免死锁的算法。在避免死锁方法中允许进程动态地申请资源,但在进行资源分配之前,应先计算此次分配资源的安全性,若分配不会导致系统进入不安全状态,则分配,否则等待。

 2.编写一个 Java 程序来实现银行家算法。几个客户申请和释放银行资源。银行家只有在系统处于安全状态时才会满足客户申请,否则请求会被拒绝。

关键步骤

操作系统|| 进程死锁与预防的银行家算法模拟_第1张图片

 (1)银行通过使用下面的数据结构来跟踪资源:

int numOfCustomers;  // the number of customers
int numOfResources;  // the number of resources
int[] available;    //the available amount of each resource1)

可利用资源向量Available是个含有m个元素的数组,其中的每一个元素代表一类可利用的资源数目。如果Available[j]=K,则表示系统中现有Rj类资源K个。

int[][] maximum;  //the maximum demand of each customer

最大需求矩阵Maximum这是一个n×m的矩阵,它定义了系统中n个进程中的每一个进程对m类资源的最大需求。如果Max[i,j]=K,则表示进程i需要Rj类资源的最大数目为K。

int[][] allocation;  //the amount currently allocated to each customer

分配矩阵Allocation这也是一个n×m的矩阵,它定义了系统中每一类资源当前已分配给每一进程的资源数。如果Allocation[i,j]=K,则表示进程i当前已分得Rj类资源的数目为K。

int[][] need;      //the remaining needs of each customer

需求矩阵Need。这也是一个n×m的矩阵,用以表示每一个进程尚需的各类资源数。如果Need[i,j]=K,则表示进程i还需要Rj类资源K个,方能完成其任务。

Need[i,j]=Max[i,j]-Allocation[i,j]

2)银行系统实现:

银行提供的接口如下:

public interface Bank
{  // Add a customer 
// customerNum - the number of the customer
// maxDemand-the maximum demand for this customer
public void addCustomer (int customerNum, int[] maxDemand) ;
// Output the value of available, maximum, allocation, need
public void getstate();
// Request resources
// customerNum-the customer requesting resources
//request-the resources being requested
public boolean requestResources (int customerNum, int [] request);
//Release resources
//customerNum - the customer releasing resources
//release - the resources being released
public void releaseResources(int customerNum, int[] release):

(3)银行家算法原理:

设Requesti是进程Pi的请求向量,如果Requesti[j]=K,表示进程Pi需要K个Rj类型的资源。当Pi发出资源请求后,系统按下述步骤进行检查:

1.如果Requesti[j]≤Need[i,j],便转向步骤(2);否则认为出错,因为它所需要的资源数已超过它所宣布最大值。

2.如果Requesti[j]≤Available[j],便转向步骤(3);否则,表示尚无足够资源,Pi须等待。

3.系统试探着把资源分配给进程Pi,并修改下面数据结构中的数值:

Available[j]=Available[j]-Requesti[j];
Allocation[i,j]=Allocation[i,j]+Requesti[j]; 
Need[i,j]=Need[i,j]-Requesti[j];

系统执行安全性算法,检查此次资源分配后,系统是否处于安全状态。若安全,才正式将资源分配给进程Pi,以完成本次分配;否则,将本次的试探分配作废,恢复原来的资源分配状态,让进程Pi等待。

(4)安全性算法

1.设置两个向量:

工作向量Work: 它表示系统可提供给进程继续运行所需的各类资源数目,它含有m个元素,在执行安全算法开始时,Work=Available;

工作向量Finish: 它表示系统是否有足够的资源分配给进程,使之运行完成。开始时先做Finish[i]=false; 当有足够资源分配给进程时, 再令Finish[i]=true。

2.从进程集合中找到一个能满足下述条件的进程:

Finish[i]=false;

Need[i,j]≤Work[j];

若找到,执行 (3),否则,执行 (4)

3.当进程Pi获得资源后,可顺利执行,直至完成,并释放出分配给它的资源,故应执行:

Work[j]= Work[i]+Allocation[i,j];

Finish[i]= true;

go to step 2;

4.如果所有进程的Finish[i]=true都满足, 则表示系统处于安全状态;否则,系统处于不安全状态

private boolean isSafeState() {
        // Check if the system is in a safe state
        boolean[] finished = new boolean[numOfCustomers];
        int[] work = Arrays.copyOf(available, available.length);

        while (true) {
            boolean found = false;
            for (int i = 0; i < numOfCustomers; i++) {
                if (!finished[i] && isRequestFeasible(i, work)) {
                    // Simulate allocating resources to customer i
                    for (int j = 0; j < work.length; j++) {
                        work[j] += allocation[i][j];
                    }
                    finished[i] = true;
                    found = true;
                }
            }
            if (!found) {
                break;
            }
        }
        // Check if all customers have finished
        for (boolean isFinished : finished) {
            if (!isFinished) {
                return false;
            }
        }
        return true;
    }

 源码

public interface Bank
{
	/**
	 * Add a customer to the bank.
	 * @param threadNum The number of the customer being added.
	 * @param maxDemand The maximum demand for this customer.
	 */
        public void addCustomer(int threadNum, int[] maxDemand);

	/**
	 * Outputs the available, allocation, max, and need matrices.
	 */
        public void getState();

	/**
	 * Make a request for resources.
	 * @param threadNum The number of the customer being added.
	 * @param request The request for this customer.
	 * @return  true The request is granted.
	 * @return  false The request is not granted.
         */
	public boolean requestResources(int threadNum, int[] request);

        /**
         * Release resources.
	 * @param threadNum The number of the customer being added.
	 * @param release The resources to be released.
         */
        public  void releaseResources(int threadNum, int[] release);
}
import java.util.Arrays;

public class BankImpl implements Bank {
    int numOfCustomers;  // the number of customers
    int numOfResources;  // the number of resources
    int[] available;    //the available amount of each resource
    int[][] maximum;  //the maximum demand of each customer
    int[][] allocation;  //the amount currently allocated to each customer
    int[][] need;      //the remaining needs of each customer

    public BankImpl(int[] initialResources) {
        available = initialResources;
        numOfResources = initialResources.length;
        maximum = new int[TestBankers.NUMBER_OF_CUSTOMERS][numOfResources];
        allocation = new int[TestBankers.NUMBER_OF_CUSTOMERS][numOfResources];
        need = new int[TestBankers.NUMBER_OF_CUSTOMERS][numOfResources];
    }

    @Override
    public void addCustomer(int threadNum, int[] maxDemand) {
        maximum[threadNum] = maxDemand.clone();
        for (int i = 0; i < numOfResources; i++) {
            need[threadNum][i] = maxDemand[i];
        }
        numOfCustomers++;
    }

    @Override
    public boolean requestResources(int threadNum, int[] request) {
        // Check if the request is valid
        if (!isRequestValid(threadNum, request)) {
            return false;
        }
        // Temporarily allocate resources to the customer
        allocateResources(threadNum, request);
        // Check if the system is in a safe state
        if (isSafeState()) {
            return true; // Approve the request
        } else {
            // Rollback
            deallocateResources(threadNum, request);
            return false; // Deny the request
        }
    }

    @Override
    public synchronized void releaseResources(int threadNum, int[] release) {
        // Release the allocated resources of the customer
        for (int i = 0; i < release.length; i++) {
            allocation[threadNum][i] -= release[i];
            available[i] += release[i];
            need[threadNum][i] += release[i];
        }
    }

    @Override
    public synchronized void getState() {
        System.out.println("Available resources:");
        System.out.println(Arrays.toString(available));
        System.out.println("Maximum demands:");
        for (int i = 0; i < maximum.length; i++) {
            for (int j = 0; j < maximum[i].length; j++) {
                System.out.print(maximum[i][j] + " ");
            }
            System.out.println();
        }
        System.out.println("Allocated resources:");
        for (int[] allocatedResource : allocation) {
            System.out.println(Arrays.toString(allocatedResource));
        }
        System.out.println();
    }

    private boolean isRequestValid(int threadNum, int[] request) {
        for (int i = 0; i < request.length; i++) {
            if (request[i] > need[threadNum][i]) {
                System.out.println("The requested amount exceeds the customer's needs");
                return false;
            }
        }
        for (int i = 0; i < request.length; i++) {
            if (request[i] > available[i]) {
                System.out.println("The requested amount exceeds the currently available resources");
                return false;
            }
        }
        return true;
    }

    private void allocateResources(int threadNum, int[] request) {
        // Allocate resources
        for (int i = 0; i < request.length; i++) {
            allocation[threadNum][i] += request[i];
            available[i] -= request[i];
            need[threadNum][i] -= request[i];
        }
    }

    private void deallocateResources(int threadNum, int[] request) {
        // Rollback the allocated resources
        for (int i = 0; i < request.length; i++) {
            allocation[threadNum][i] -= request[i];
            available[i] += request[i];
            need[threadNum][i] += request[i];
        }
    }

    private boolean isSafeState() {
        // Check if the system is in a safe state
        boolean[] finished = new boolean[numOfCustomers];
        int[] work = Arrays.copyOf(available, available.length);

        while (true) {
            boolean found = false;
            for (int i = 0; i < numOfCustomers; i++) {
                if (!finished[i] && isRequestFeasible(i, work)) {
                    // Simulate allocating resources to customer i
                    for (int j = 0; j < work.length; j++) {
                        work[j] += allocation[i][j];
                    }
                    finished[i] = true;
                    found = true;
                }
            }
            if (!found) {
                break;
            }
        }
        // Check if all customers have finished
        for (boolean isFinished : finished) {
            if (!isFinished) {
                return false;
            }
        }
        return true;
    }

    private boolean isRequestFeasible(int threadNum, int[] work) {
        for (int i = 0; i < work.length; i++) {
            // Maximum demand - Allocated resources = need > Currently available resources
            if (need[threadNum][i] > work[i]) {
                return false;
            }
        }
        return true;
    }
}
import java.io.*;
import java.util.Arrays;
import java.util.StringTokenizer;

public class TestBankers
{
	public static final int NUMBER_OF_CUSTOMERS = 5;

	public static void main(String[] args) throws IOException {
		if (args.length < 1) {
			System.err.println("Usage java TestHarness    ...");
			System.exit(-1);
		}

		// get the name of the input file
		String inputFile = args[0];

		// now get the resources
		int numOfResources = args.length-1;

		// the initial number of resources
		int[] initialResources= new int[numOfResources];

		// the resources involved in the transaction
		int[] resources= new int[numOfResources];
		for (int i = 0; i < numOfResources; i++)
			initialResources[i] = Integer.parseInt(args[i+1].trim());

		// create the bank
		Bank theBank = new BankImpl(initialResources);
		int[] maxDemand = new int[numOfResources];

		// read initial values for maximum array
		String line;
		try {
			@SuppressWarnings("resource")
			BufferedReader inFile = new BufferedReader(new FileReader(inputFile));

			int threadNum = 0;
			int resourceNum = 0;

			for (int i = 0; i < NUMBER_OF_CUSTOMERS; i++) {
				line = inFile.readLine();
				StringTokenizer tokens = new StringTokenizer(line,",");

				while (tokens.hasMoreTokens()) {
					int amt = Integer.parseInt(tokens.nextToken().trim());
					maxDemand[resourceNum++] = amt;
				}
				theBank.addCustomer(threadNum,maxDemand);
				++threadNum;
				resourceNum = 0;
			}
		}
		catch (FileNotFoundException fnfe) {
			throw new Error("Unable to find file " + inputFile);
		}
		catch (IOException ioe) {
			throw new Error("Error processing " + inputFile);
		}

		// now loop reading requests

		BufferedReader cl = new BufferedReader(new InputStreamReader(System.in));
		@SuppressWarnings("unused")
		int[] requests = new int[numOfResources];
		String requestLine;

		while ( (requestLine = cl.readLine()) != null) {
			if (requestLine.equals(""))
				continue;

			if (requestLine.equals("*"))
				// output the state
				theBank.getState();
			else {
				// we know that we are reading N items on the command line
				// [RQ || RL]   <#2> <#3>
				StringTokenizer tokens = new StringTokenizer(requestLine);

				// get transaction type - request (RQ) or release (RL)
				String trans = tokens.nextToken().trim();

				// get the customer number making the transaction
				int custNum = Integer.parseInt(tokens.nextToken().trim());

				// get the resources involved in the transaction
				for (int i = 0; i < numOfResources; i++) {
					resources[i] =Integer.parseInt(tokens.nextToken().trim());
					System.out.println("*"+resources[i]+"*");
				}

				// now check the transaction type
				if (trans.equals("RQ")) {  // request
					if (theBank.requestResources(custNum,resources))
						System.out.println("Approved");
					else
						System.out.println("Denied");
				}
				else if (trans.equals("RL")) // release
					theBank.releaseResources(custNum, resources);
				else // illegal request
					System.err.println("Must be either 'RQ' or 'RL'");
			}
		}
	}
}

结果

操作系统|| 进程死锁与预防的银行家算法模拟_第2张图片

你可能感兴趣的:(算法,Java,银行家算法,进程死锁)