강상위

Add 02_operating_systems

# Operating Systems - Coding Assignment1: safety algorithm
- [Coding Assignment1]safety_algorithm.py
- [Coding Assignment1]r_SafeCaseResult.png
- [Coding Assignment1]r_UnsafeCaseResult.png
- (ref)ref_safety_algorithm.py
- (ref)ref_safety_algorithm2.py
- (ref)ref_safety_algorithm3.py
# Operating Systems - Coding Assignment2: memory allocation
- [Coding Assignment2]memory_allocation.py
- processes.txt
\ No newline at end of file
#_*_ coding: utf-8 _*_
process_num = 4 #process 갯수
resource_num = 3 #resourse 종류
resource_max = []
finished_process = [] # process 수행종료 여부
alloc = [] # 각 process의 초기할당
process_max = [] # 각 process의 max
avail = [] # 각 process의 available
need = [] # 각 process의 need
safety_order = [] # safe한 process의 순서를 나타냄
def main() :
# 초기 설정 작업 #
# finished_process 계산
for i in range(0, process_num) :
finished_process.append(False)
safety_order.append(0)
while(1) :
print("\nPlease Enter 1 to Safe Case")
print("or 2 to Unsafe Case")
choice = int(input("Enter : "))
if(choice == 1) :
# Safe Case의 각 resource 상한과 현재 할당량, process별 상한 지정
resource_max = [20,30,40]
alloc = [[0,5,1],[2,2,2],[1,2,1],[2,8,18]]
process_max = [[10,15,4],[2,25,35],[17,20,30],[10,19,20]]
for j in range(0, resource_num) : # avail 계산
temp = resource_max[j]
for i in range(0,process_num) :
temp -= alloc[i][j]
avail.append(temp)
for i in range(0, process_num) : # need 계산
temp = []
for j in range(0, resource_num) :
temp.append(abs(process_max[i][j]-alloc[i][j]))
need.append(temp)
break
elif(choice == 2) :
# Unsafe Case의 각 resource 상한과 현재 할당량, process별 상한 지정
resource_max = [20,30,40]
alloc = [[0,5,1],[2,2,2],[1,2,1],[2,8,18]]
process_max = [[20,15,4],[2,25,35],[19,20,30],[15,19,20]]
for j in range(0, resource_num) : # avail 계산
temp = resource_max[j]
for i in range(0,process_num) :
temp -= alloc[i][j]
avail.append(temp)
for i in range(0, process_num) : # need 계산
temp = []
for j in range(0, resource_num) :
temp.append(abs(process_max[i][j]-alloc[i][j]))
need.append(temp)
break
else :
print("Please Enter Right Value!")
# 현재상황 출력
print("\n--------------Safety Algorithm--------------\n")
print("Current Allocation : [A, B, C]")
for i in range(0, process_num) :
print(" P#"+str(i+1)+" : "+str(alloc[i]))
print("\n Current Max : [A, B, C]")
for i in range(0, process_num) :
print(" P#"+str(i+1)+" : "+str(process_max[i]))
# 비교 및 순서도출
time = 0
while(time < process_num) :
for i in range(0, process_num) :
k = 0
for j in range(0,resource_num) :
if(need[i][j] <= avail[j]) :
k += 1 # 해당 process가 available보다 작은 need를 가졌다면 count
if(k == resource_num) : # 해당 process의 모든 resource가 available보다 작은 need를 가진 경우
finished_process[i] = True # 해당 process는 finish 했다고 표시됨
for l in range(0, resource_num) :
avail[l] = avail[l] + alloc[i][l] # 자신이 할당했던 resource를 환원하고
need[i][l] = 10000 # 끝난 process는 need값을 많이 높여 비교대상에서 제외
safety_order[time] = i # safety_order에 현재 time에 적합한 process의 index를 설정
break
time += 1
time = 0
for i in range(0, process_num) :
if(finished_process[i] == True) :
time += 1 # i값에 따라 True인 process를 찾고 time을 증가시킨다
if(time == process_num) : # 모든 process가 True여야만 Safe Case이다.
result = ""
for i in range(0, process_num) :
result = result + "Process#" + str(safety_order[i]+1) + "/"
print("\n Safe Processes! : " + result)
else :
print("\nNot Safe Processes!")
print("\n--------------------------------------------\n")
if __name__ == '__main__' :
main()
# -*- coding: utf-8 -*-
# Node 클래스 정의
class Node:
def __init__(self, pnum, psize):
self.pnum = pnum
self.psize = psize
self.next = None
# 자료구조 정의
class MemoryList:
total_memory = 1000.0
available_memory = total_memory
# 초기화 메소드
def __init__(self):
dummy = Node(0,0.0)
self.head = dummy
self.tail = dummy
self.current = None
self.before = None
self.alloc_ptr = None
self.searching_ptr = None
self.hole = 0
self.hole_found = None
self.num_of_data = 0
# self.allocMemory(0,self.total_memory)
# allocMemory 메소드
def allocMemory(self, pnum, psize):
if(psize != 0) :
if(self.available_memory<psize) :
print("Not enough memory!")
# 처음인 경우 그냥 넣고
elif((self.num_of_data == 0)or(self.hole==0)) :
new_node = Node(pnum, psize)
self.available_memory -= psize
self.tail.next = new_node
self.tail = new_node
self.num_of_data += 1
# 첫 할당이 아닐 경우는 alloc_ptr 초기화 해서 사용합니다.
else :
self.first()
self.alloc_ptr = self.current
self.searching_ptr = self.current
# best를 찾기 위한 변수
best_fit = 10000
self.hole_found = False
while(True) :
# pnum = 0(빈자리) 중 psize보다 큰 자리가 있으면
if((self.searching_ptr.pnum==0)and(self.searching_ptr.psize>=psize)) :
self.hole_found = True
# best fit 계산해보고, alloc_ptr 설정
if(best_fit>(self.searching_ptr.psize-psize)) :
best_fit = self.searching_ptr.psize-psize
self.alloc_ptr = self.searching_ptr
# 마지막까지 갔으면 break!
if(self.searching_ptr.next == None) :
self.searching_ptr = None
break
self.searching_ptr = self.searching_ptr.next
if(self.hole_found == True) :
# new_node를 뒤에 붙일 노드로 초기화
new_node = Node(0, (self.alloc_ptr.psize-psize))
new_node.next = self.alloc_ptr.next
self.alloc_ptr.next = new_node
self.alloc_ptr.pnum = pnum
self.alloc_ptr.psize = psize
if(new_node.psize == 0) :
self.alloc_ptr.next = new_node.next
new_node.next = None
self.available_memory -= psize
self.num_of_data += 1
elif(self.hole_found == False) :
new_node = Node(pnum, psize)
self.tail.next = new_node
self.tail = new_node
self.available_memory -= psize
self.num_of_data += 1
elif(psize == 0) :
self.first()
while(True) :
if(self.current.pnum == pnum) :
self.current.pnum = 0
self.available_memory += self.current.psize
self.hole += 1
break
else :
self.next()
# def delete(self):
# # pop_pnum = self.current.pnum
# # pop_psize = self.current.psize
# if self.current is self.tail:
# self.tail = self.before
# self.before.next = self.current.next
# self.current = self.before # 중요 : current가 next가 아닌 before로 변경된다.
# #
# self.num_of_data -= 1
# return pop_pnum, pop_psize
# first 메소드 (search1 - 맨 앞의 노드 검색, before, current 변경)
def first(self):
if self.num_of_data == 0: # 데이터가 없는 경우 첫번째 노드도 없기 때문에 None 리턴
return None
self.before = self.head
self.current = self.head.next
# return self.current.psize, self.current.pnum
# next 메소드 (search2 - current 노드의 다음 노드 검색, 이전에 first 메소드가 한번은 실행되어야 함)
def next(self):
if self.current.next == None:
# print ("End")
return None
else :
self.before = self.current
self.current = self.current.next
return self.current.pnum, self.current.psize
def size(self):
return self.num_of_data
myMemory = MemoryList()
# 파일 open & process 할당.
f = open('processes.txt','r')
i = 1
print("\n[Memory Size : 1000.0]\n")
while(True) :
line = f.readline().strip().split()
if(not line) : break
myMemory.allocMemory(int(line[0]), float(line[1]))
myMemory.first()
print("REQUEST#"+str(i)+" - Process#"+str(line[0])+" "+str(line[1]))
while(True) :
if(myMemory.current.pnum!=0) :
print("Process#" + str(myMemory.current.pnum) + ": " + str(myMemory.current.psize))
else :
print(" Hole: "+str(myMemory.current.psize))
if(myMemory.next()==None) :
break
print("Available Memory: "+str(myMemory.available_memory)+"\n")
i += 1
# print(pdict)
f.close()
# ---------- Testing ----------#
# myMemory.allocMemory(1,22.0)
# myMemory.allocMemory(2,18.0)
# myMemory.allocMemory(3,28.0)
# myMemory.allocMemory(5,25.0)
# myMemory.allocMemory(4,5.0)
# myMemory.allocMemory(2,0)
# myMemory.allocMemory(6,10.0)
# # myMemory.allocMemory(4,0)
# myMemory.allocMemory(5,0)
# myMemory.allocMemory(7,20.0)
# print("MEMORY SIZE: "+str(myMemory.total_memory)+"\n")
# print("REQUEST 1: 22.0")
# print("Best Fit: Allocated at address "+str(myMemory.current.psize))
# print(" "+str(myMemory.available_memory)+" free")
1 100
2 100
3 100
4 80
5 100
4 0
6 100
7 100
8 88
9 23
10 22
9 0
11 67
4 50
7 0
11 0
12 100
13 100
12 0
14 99
from string import ascii_uppercase
letters = list(ascii_uppercase)
def main():
available = []
original_available = []
process = []
total_allocation = []
total_resources = []
# f(x1)
number_of_resources = 3
number_of_processes = 4
# f(x2)
total_resources = set_total_resources(number_of_resources=number_of_resources)
# f(x3)
process = set_processes(number_of_resources=number_of_resources, number_of_processes=number_of_processes)
total_allocation = get_total_allocation(process=process, number_of_processes=len(process), number_of_resources=number_of_resources)
available = get_available(total_resources=total_resources, total_allocation=total_allocation, number_of_resources=number_of_resources)
original_available = list(available)
# f(x4)
process = get_process_need(process=process, number_of_processes=len(process), number_of_resources=number_of_resources)
temp = list(process)
# f(x5)
while (len(process) != 0):
queue, process = compare_ai_need(available=available, process=process, number_of_processes=len(process), number_of_resources=number_of_resources)
# f(x6)
available = get_new_ai(available=available, queue=queue, number_of_processes=len(queue), number_of_resources=number_of_resources)
# f(x7)
is_safe, available = check_safety(original_available=original_available, available=available, total_allocation=total_allocation, number_of_resources=number_of_resources)
process = list(temp)
print("Total Resources : {}".format(total_resources))
print("Total Allocation : {}".format(total_allocation))
print("Original Available Instance : {}".format(original_available))
print("New Available Instance : {}".format(available))
print("Processes : {}".format(process))
print("Safe" if is_safe == True else "Not Safe")
def set_total_resources(number_of_resources=0):
total_resources = []
for resource_number in range(0, number_of_resources):
total_resources.append(int(input("Total Resources, value for {}: ".format(letters[resource_number]))))
return total_resources
def set_processes(number_of_resources=0, number_of_processes=0):
cur_allocation = []
max_allocation = []
process = []
for index in range(0, number_of_processes):
for resource_number in range(0, number_of_resources):
max_allocation.append(int(input("Max. Allocation #{}, value for {}: ".format(index + 1, letters[resource_number]))))
for resource_number in range(0, number_of_resources):
cur_allocation.append(int(input("Cur. Allocation #{}, value for {}: ".format(index + 1, letters[resource_number]))))
process.append([max_allocation, cur_allocation])
max_allocation = []
cur_allocation = []
return process
def get_total_allocation(process=[], number_of_processes=0, number_of_resources=0):
summation = 0
total_allocation = []
for resource_number in range(0, number_of_resources):
for index in range(0, number_of_processes):
summation += process[index][1][resource_number]
total_allocation.append(summation)
summation = 0
return total_allocation
def get_available(total_resources=[], total_allocation=[], number_of_resources=0):
available = list([abs(rn_total_resources - rn_total_allocation) for rn_total_resources, rn_total_allocation in zip(total_resources, total_allocation)])
return available
def get_process_need(process=[], number_of_processes=0, number_of_resources=0):
for index in range(0, number_of_processes):
need = list([abs(rn_max_alloc - rn_current_alloc) for index, rn_max_alloc, rn_current_alloc in zip(process, process[index][0], process[index][1])])
process[index].append(need)
need = []
return process
def compare_ai_need(available=[], process=[], number_of_processes=0, number_of_resources=0):
for_removal = []
queue = []
for index in range(0, number_of_processes):
if (process[index][2] < available):
queue.append([process[index][2], process[index][0]])
for_removal.append(process[index])
queue.sort()
for index in range(0, len(for_removal)):
process.remove(for_removal[index])
return queue, process
def get_new_ai(available=[], queue=[], number_of_processes=0, number_of_resources=0):
for index in range(0, number_of_processes):
for resource_number in range(0, number_of_resources):
available[resource_number] = abs(available[resource_number] - queue[index][0][resource_number]) + queue[index][1][resource_number]
return available
def check_safety(original_available=[], available=[], total_allocation=[], number_of_resources=0):
available = list([abs(rn_available - rn_total_allocation) for rn_available, rn_total_allocation in zip(available, total_allocation)])
return (True if (original_available == available) else False), available
if __name__ == '__main__':
main()
\ No newline at end of file
#_*_ coding: utf-8 _*_
from string import ascii_uppercase
letters = list(ascii_uppercase)
def main() :
available = []
original_available = []
process = []
finished_process = []
finished = False
total_allocation = []
# resource는 3종류이며, 각각 20, 30, 40을 가지고 있다.
number_of_resources = 3
total_resources = [20,30,40]
# process는 4개가 있다.
number_of_processes = 4
# [ process:[[max],[current]], ...]
process = [[[10,6,4],[0,1,1]],[[5,6,7],[2,2,2]],[[15,3,4],[1,2,2]],[[7,9,20],[2,8,11]]]
# total_allocation, available, original_available 계산
total_allocation = get_total_allocation(process, number_of_processes, number_of_resources)
available = get_total_available(total_resources, total_allocation, number_of_resources)
original_available = available
# finish 설정
for i in range(0,number_of_processes) :
finished_process.append(False)
print(" total_resources : " + str(total_resources))
print("total_allocation : " + str(total_allocation))
print(" available : " + str(available))
print(" finish : " + str(finished_process))
get_process_need(process, number_of_processes, number_of_resources)
print("\n process : Max Allocation Need")
for i in range(0, number_of_processes) :
print(" " + str(process[i]))
temp = list(process)
while(len(process) != 0) :
queue, process = compare_avail_need(available, process, number_of_processes, number_of_resources)
available = get_new_avail(available, queue, len(queue), number_of_resources)
is_safe, available = check_safety(original_available, available, total_allocation, number_of_resources)
process = list(temp)
print("New available instances : " + str(available))
print(" Processes : " + str(process))
print(" Safe" if is_safe==True else " Not Safe")
def get_total_allocation(process, number_of_processes, number_of_resources) :
sum = 0
temp = []
# 각 process들의 현재 할당된 resource를 더해서 현재 전체 사용중인 resource 도출
for i in range(0, number_of_resources) :
for j in range(0, number_of_processes) :
sum += process[j][1][i]
temp.append(sum)
sum = 0
return temp
def get_total_available(total_resources, total_allocation, number_of_resources) :
temp = []
# 현재 사용 가능한 resource를 계산
for i in range(0,number_of_resources) :
temp.append(total_resources[i] - total_allocation[i])
return temp
def get_process_need(process, number_of_processes, number_of_resources) :
need = []
for i in range(0, number_of_processes) :
for j in range(0, number_of_resources) :
need.append(process[i][0][j] - process[i][1][j])
process[i].append(need)
need = []
def compare_avail_need(available, process, number_of_processes, number_of_resources) :
remove_list = []
queue = []
for i in range(0, number_of_processes) :
if(process[i][2] < available) :
queue.append([process[i][2], process[i][0]])
remove_list.append(process[i])
queue.sort()
for i in range(0, len(remove_list)) :
process.remove(remove_list[i])
return queue, process
def get_new_avail(available, queue, number_of_processes, number_of_resources) :
for i in range(0, number_of_processes) :
for j in range(0, number_of_resources) :
available[j] = abs(available[j] - queue[i][0][j]) + queue[i][1][j]
return available
def check_safety(original_available, available, total_allocation, number_of_resources) :
available = list([abs(rn_available - rn_total_allocation) for rn_available, rn_total_allocation in zip(available, total_allocation)])
return (True if (original_available == available) else False), available
if __name__ == '__main__' :
main()
#_*_ coding: utf-8 _*_
process_num = 4 #process 갯수
resource_num = 3 #resourse 종류
resource_max = []
finished_process = [] # process 수행종료 여부
alloc = [] # 각 process의 초기할당
process_max = [] # 각 process의 max
avail = [] # 각 process의 available
need = [] # 각 process의 need
safety_order = [] # safe한 process의 순서를 나타냄
def main() :
# 초기 설정 작업 #
# finished_process 계산
for i in range(0, process_num) :
finished_process.append(False)
safety_order.append(0)
while(1) :
print("\nPlease Enter 1 to Safe Case")
print("or 2 to Unsafe Case")
choice = int(input("Enter : "))
if(choice == 1) :
# Safe Case의 각 resource 상한과 현재 할당량, process별 상한 지정
resource_max = [20,30,40]
alloc = [[0,5,1],[2,2,2],[1,2,1],[2,8,18]]
process_max = [[10,15,4],[2,25,35],[17,20,30],[10,19,20]]
for j in range(0, resource_num) : # avail 계산
temp = resource_max[j]
for i in range(0,process_num) :
temp -= alloc[i][j]
avail.append(temp)
for i in range(0, process_num) : # need 계산
temp = []
for j in range(0, resource_num) :
temp.append(abs(process_max[i][j]-alloc[i][j]))
need.append(temp)
break
elif(choice == 2) :
# Unsafe Case의 각 resource 상한과 현재 할당량, process별 상한 지정
resource_max = [20,30,40]
alloc = [[0,5,1],[2,2,2],[1,2,1],[2,8,18]]
process_max = [[20,15,4],[2,25,35],[19,20,30],[15,19,20]]
for j in range(0, resource_num) : # avail 계산
temp = resource_max[j]
for i in range(0,process_num) :
temp -= alloc[i][j]
avail.append(temp)
for i in range(0, process_num) : # need 계산
temp = []
for j in range(0, resource_num) :
temp.append(abs(process_max[i][j]-alloc[i][j]))
need.append(temp)
break
else :
print("Please Enter Right Value!")
# 현재상황 출력
print("\n--------------Safety Algorithm--------------\n")
print("Current Allocation : [A, B, C]")
for i in range(0, process_num) :
print(" P#"+str(i+1)+" : "+str(alloc[i]))
print("\n Current Max : [A, B, C]")
for i in range(0, process_num) :
print(" P#"+str(i+1)+" : "+str(process_max[i]))
# 비교 및 순서도출
time = 0
while(time < process_num) :
for i in range(0, process_num) :
k = 0
for j in range(0,resource_num) :
if(need[i][j] <= avail[j]) :
k += 1 # 해당 process가 available보다 작은 need를 가졌다면 count
if(k == resource_num) : # 해당 process의 모든 resource가 available보다 작은 need를 가진 경우
finished_process[i] = True # 해당 process는 finish 했다고 표시됨
for l in range(0, resource_num) :
avail[l] = avail[l] + alloc[i][l] # 자신이 할당했던 resource를 환원하고
need[i][l] = 10000 # 끝난 process는 need값을 많이 높여 비교대상에서 제외
safety_order[time] = i # safety_order에 현재 time에 적합한 process의 index를 설정
break
time += 1
time = 0
for i in range(0, process_num) :
if(finished_process[i] == True) :
time += 1 # i값에 따라 True인 process를 찾고 time을 증가시킨다
if(time == process_num) : # 모든 process가 True여야만 Safe Case이다.
result = ""
for i in range(0, process_num) :
result = result + "Process#" + str(safety_order[i]+1) + "/"
print("\n Safe Processes! : " + result)
else :
print("\nNot Safe Processes!")
print("\n--------------------------------------------\n")
if __name__ == '__main__' :
main()
No preview for this file type
# Operating Systems - Java Lab
- Java Lab files
\ No newline at end of file
import java.util.Scanner;
public class lecture3{
public static void main(String args[]){
/*
int num;
System.out.print("Enter Number : ");
Scanner input = new Scanner(System.in);
num = input.nextInt();
if(num%5 == 0)
System.out.println("HiFive");
else if(num%2 == 0)
System.out.println("HiEven");
else
System.out.println("HiOdd");
*/
/*
float bmi;
System.out.print("Enter Weight : ");
Scanner input = new Scanner(System.in);
bmi = input.nextFloat();
if(bmi<18.5){
System.out.println("Underweight");
}
else if(bmi<25){
System.out.println("Normal");
}
else if(bmi<30){
System.out.println("Overweight");
}
else{
System.out.println("Obese");
}
*/
int x = 1;
System.out.println((x > 1) & (x++ < 10));
System.out.println((1 > x) && ( 1 > x++));
System.out.println((1 == x) | (10 > x++));
System.out.println((1 == x) || (10 > x++));
}
}
import java.util.Scanner;
public class lecture4{
public static void main(String args[]){
System.out.println("Test");
System.out.println("Hi Hi");
}
}
import java.util.Scanner;
import java.lang.Math;
public class test{
public static void main(String args[]){
double radius;
double area;
Scanner input = new Scanner(System.in);
System.out.print("Enter a double value: ");
radius = input.nextDouble();
//radius = 20;
area = Math.pow(radius, 2) * 3.14159;
System.out.println(area);
}
}
\ No newline at end of file
import java.util.Scanner;
import java.lang.Math;
public class test2{
public static void main(String args[]){
double fahrenheit;
double celcious;
Scanner input = new Scanner(System.in);
System.out.print("Enter a fahrenheit degree: ");
fahrenheit = input.nextDouble();
celcious = (5.0 / 9)*(fahrenheit 32);
System.out.println(fahrenheit+"fahrenheit degree is "+celcious+"celcious degree");
}
}
\ No newline at end of file
# Operating Systems
- Coding Assignment
- Java Lab
# 2018-1st University Semester Lecture Files
- 01.Algorithm Analysis / 2018.9.14. Add / 2018.3 ~ 2018.6
- 02.Operating Systems / 2018.9.16. Add / 2018.3 ~ 2018.6
......