round_robin.py

an anonymous user · May 09, 2023
#round robin or time slice scheduling

#simulate the round robin scheduling algorithm
#we are given threads and their processing times
#we need to calculate waiting time for each thread and average waiting time

def round_robin(threads, processing_times):

    #create a tuple of (thread, processing_time)
    #and add it to the queue
    queue = []
    for i in range(len(threads)):
        queue.append((threads[i], processing_times[i]))

    #sort queue in increasing order of processing times
    queue.sort(key=lambda x: x[1])

    #create a queue for waiting times for each thread
    wq = []
    for i in range(len(threads)):
        wq.append(0)

    #loop through the queue, and calculate waiting times
    #for each thread
    for i in range(len(queue)):
        #waiting time for first thread is: number of threads * processing time
        #waiting time for conequential threads is: 
        # waiting time of previous thread + (num of remaining threads * (processing time of that thread - processing time of previous thread))
        if i == 0:
            wq[i] = len(queue) * queue[i][1]
        else:
            wq[i] = wq[i - 1] + (len(queue) - i) * (queue[i][1] - queue[i - 1][1])

    #calculate average waiting time
    avg_wt = 0
    for i in range(len(wq)):
        avg_wt += wq[i]
    avg_wt /= len(wq)

    #print the table
    print("Thread | Processing Time | Waiting Time")
    for i in range(len(queue)):
        print(queue[i][0], "   |", queue[i][1], "           |", wq[i])

    #print average waiting time
    print("Average waiting time:", avg_wt)

#test the function
threads = ['A', 'B', 'C', 'D']
processing_times = [6, 9, 8, 10]
round_robin(threads, processing_times)



    
    
Output

Comments

Please sign up or log in to contribute to the discussion.