两川 2024-10-09 14:57
浏览 5
已结题

操作系统Python


def is_safe_state(processes, available, allocation, need):
    work = available.copy()
    finish = [False] * len(processes)
    safe_sequence = []

    while len(safe_sequence) < len(processes):
        allocated_this_round = False
        for i in range(len(processes)):
            if not finish[i] and all(need[i][j] <= work[j] for j in range(len(available))):
                # 如果进程i可以完成
                for j in range(len(available)):
                    work[j] += allocation[i][j]
                finish[i] = True
                safe_sequence.append(i)
                allocated_this_round = True
                break
        if not allocated_this_round:
            # 如果没有进程可以完成,则系统处于不安全状态
            return False, []

    return True, safe_sequence

def can_allocate_resources(processes, available, allocation, need, request, process_index):
    # 尝试分配资源给指定的进程
    temp_available = available.copy()
    temp_allocation = [list(a) for a in allocation]
    temp_need = [list(n) for n in need]

    for i in range(len(request)):
        if request[i] > temp_available[i]:
            return False, "资源不足,无法分配"

    # 尝试分配
    for i in range(len(request)):
        temp_available[i] -= request[i]
        temp_allocation[process_index][i] += request[i]
        temp_need[process_index][i] -= request[i]

    # 检查分配后的状态是否安全
    is_safe, _ = is_safe_state(processes, temp_available, temp_allocation, temp_need)
    if is_safe:
        return True, temp_allocation
    else:
        return False, "分配资源后状态不安全"

# 定义进程、可用资源、已分配资源和需求矩阵
processes = [
    (0, [0, 1, 2, 2], [1, 6, 5, 2]),  # P0
    (1, [1, 3, 5, 4], [2, 3, 5, 6]),  # P1,根据图片信息补全
    (2, [1, 2, 2, 2], [3, 5, 6, 0]),  # P2
    (3, [0, 3, 3, 2], [0, 6, 5, 6]),  # P3,根据图片信息补全
    (4, [0, 1, 4, 6], [0, 1, 5, 0]),  # P4,根据图片信息补全,但注意需求应为非负整数
]

available = [3, 3, 2, 2]  # 根据图片信息补全
allocation = [
    [0, 1, 0, 2],  # P0
    [2, 0, 0, 0],  # P1
    [0, 3, 3, 2],  # P2
    [0, 0, 2, 4],  # P3
    [0, 1, 0, 0],  # P4
]  # 根据图片信息补全

need = [
    list(p[2]) - list(a) for p, a in zip(processes, allocation)
]

# (1) 检查当前状态是否安全
is_safe, safe_sequence = is_safe_state(processes, available, allocation, need)
print(f"(1) 该状态是否安全? {'安全' if is_safe else '不安全'}")
if is_safe:
    print(f"    安全序列为:{safe_sequence + 1}(注意:进程编号从1开始)")

# (2) 检查P2提出请求Request(1,2,2,2)后,系统能否将资源分配给它
can_allocate, result = can_allocate_resources(processes, available, allocation, need, [1, 2, 2, 2], 2)
print(f"(2) 若进程P2提出请求Request(1,2,2,2)后,系统能否将资源分配给它? {'可以' if can_allocate else '不可以'}")
if can_allocate:
    print(f"    分配后的资源情况为:{result}")
else:
    print(f"    {result}")
  • 写回答

1条回答 默认 最新

  • 两川 2024-10-09 15:17
    关注
    
    # -*- coding: utf-8 -*-
    """
    Created on Wed Oct  9 15:11:29 2024
    
    @author: H3C
    """
    
    
    
    import numpy as np
     
    allocation = np.array([[0, 0, 3, 2], [1, 0, 0, 0], [1, 3, 5, 4], [0, 3, 3, 2], [0, 0, 1, 4]])
    need = np.array([[0, 0, 1, 2], [1,7, 5, 0], [2, 3, 5, 6], [0, 6, 5, 2], [0, 6 ,5 ,6]])
    available = np.array([1, 6, 2, 2])
    
     
    def list_convert_nparray(arg):
        return np.array(list(map(int, arg.split(','))))
     
     
    
    def banker(index, request, allocation, need, available):
        print(index, '  request:', request)
        if np.all(request <= need[index, :], axis=0) and np.all(request <= available, axis=0):
            saftySeq = []
            available -= request
            allocation[index, :] += request
            need[index, :] -= request
            work = workPlusAllocation = available
            sumOfProcess = len(allocation) 
            while len(saftySeq) < sumOfProcess:
                for i in range(0, sumOfProcess):
                    cnt = 0
                    if len(saftySeq) == sumOfProcess:
                        break
                    if i not in saftySeq and np.all(need[i, :] <= workPlusAllocation, axis=0):
                        if len(saftySeq) != 0:
                            work = workPlusAllocation
                        workPlusAllocation = work + allocation[i, :]
                        saftySeq.append(i)
                        print('Process:', i, '  Work:', work, '  Need:', need[i], '  Allocation:', allocation[i],
                              '  Work+Allocation:', workPlusAllocation)
                        cnt += 1
                    if i == sumOfProcess - 1 and cnt == 0:
                        available += request
                        allocation[index, :] -= request
                        need[index, :] += request
                        return False
            print('Safty Sequence: ', saftySeq)
            return True
        else:
            return False
     
     
    if __name__ == '__main__':
        while True:
            print('Need:\n',need)
            print('Allocation:\n',allocation)
            print('Available:',available)
            if banker(int(input("index:")), list_convert_nparray(input("request(split by ,):")), allocation, need, available):
                print("Allocate Successfully")
            else:
                print('Can not Allocate')
            print('-------------------------------')
    
    评论

报告相同问题?

问题事件

  • 系统已结题 10月17日
  • 创建了问题 10月9日