CPU scheduling simulation using Pygame

CPU scheduling simulation using Pygame

A simulation of CPU scheduling algorithms using pygame

Introduction

Pygame is a python gaming library used to make simple 2D games, but I have used this library to create a simulation of CPU scheduling algorithms. If you are new to pygame read the basics here.

CPU scheduling

CPU Scheduling is a process of determining which process will be executed in the CPU while other processes are on hold. The process here describes task such as opening a web browser, refreshing your screen etc.. One core can handle one process at a time, and the CPU scheduling is used to determine the order of execution of processes.

Algorithms

  • FCFS
  • SJF
  • Round Robin

    The algorithms are used to sort the processes for execution based on different criteria. In FCFS the process which comes first will be executed first, but this method has a disadvantage when the first process takes a lot of time to complete

    The SJF sorts the processor based on the time required for execution and sends the process with the lowest execution time first.

    Round Robin is like simultaneous execution of multiple process, a process is slit into many small processes and there are completed one by one finally completing the whole process

Pygame implemtation

Circles represent processor and CPU is represented by blocks. The processor goes into first block and after finishing it's job, goes out of the block, then the next process comes to the next block and the process repeats.

Font used

I have used Comics Sans MS font.

pygame.font.SysFont('Comic Sans MS', size, pygame.font.Font.bold)

Circles

Handling movement of circle is not as easy as square, so I have used the shape of a rectangle as x and y coordinates for circle.

cir_rect=pygame.rect.Rect(0,0,x,y)
 cir = pygame.draw.circle(SCREEN, (212, 255, 0), cir_rect.size, 20, 0)

Then we can update x and y, then finally update the rectangle using rect.update() method,

 x=x+1
 cir_rect.update(0,0,x,y)

Blocks

Simple rectangles are used for drawing blocks.

rex=pygame.rect.Rect(700, 300, 120, 50)
pygame.draw.rect(SCREEN, "Blue", rex)

Font integration

The time required for the process to complete is written at the center of the process circle. This is done by getting the exact coordinates of the circle and using blit() to render it.

 Cir_TEXT = get_font(18).render("20", True, "Red")
 Cir_RECT = Cir_TEXT.get_rect(center=cir_rect.size)
 SCREEN.blit(PLAY_TEXT, PLAY_RECT)

Conclusion

The full project is available in Github. Pygame is not only for games, we can also create such simulations which can help us understand the concepts better in both CPU scheduling and pygame.

Did you find this article valuable?

Support hari hara sankar by becoming a sponsor. Any amount is appreciated!