First Fit program in Python

Memory management is one of the most important tasks of the operating system. Processes are allocated empty memory blocks as per the process demands. This allocation takes place dynamically at the run time. For this, the operating system uses three most common memory management schemes. These are First fit, best fit, and worst fit memory allocation schemes.

In the case of first fit memory allocation, the operating system allocates memory as soon as it finds an empty memory location which is equal to or greater than the demanded memory by the process. The technique does not scans the further memory slots and returns to another task immediately. One of the biggest disadvantage of this process is, huge amount of free memory is wasted in the memory allocation scheme.

 

Program for First Fit in PYTHON

def FirstFit(block_Size, m, process_Size, n): 
          
# code to store the block id of the block that needs to be allocated to a process
allocate = [-1] * n  
  
    # Any process is assigned with the memory at the initial stage 
  
    # find a suitable block for each process 
    # the blocks are allocated as per their size 
  
    
    for i in range(n): 
        for j in range(m): 
            if block_Size[j] >= process_Size[i]: 
                  
                # assign the block j to p[i] process  
                allocate[i] = j  
  
                # available block memory is reduced   
                block_Size[j] -= process_Size[i]  
  
                break

      
              print(" Process Number Process Size Block Number")
 
              for i in range(n): 
    
              print(" ", i + 1, "      ", process_Size[i], " ", end = " ") 

    
                if allocate[i] != -1:  

                    print(allocate[i] + 1)
     else: 
    
                 print ("Not Allocated") 
  
# Driver code  
    
          if __name__ == '__main__':  
          b_Size = [100, 500, 200, 300, 600]  
          p_Size = [212, 417, 112, 426] 
          m = len(block_Size) 
          n = len(process_Size) 
      
         FirstFit(block_Size, m, process_Size, n) 
      
Output: Process Number Process Size Block Number 1 212 2 2 417 5 3 112 2 4 426 Not Allocated