-
-
Save oriapp/c211be56179c08233121276baa40223e to your computer and use it in GitHub Desktop.
Round Robin PoC
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#include <unistd.h> | |
#define QUANTUM 4 // time slice in milliseconds | |
// structure to represent a task | |
typedef struct task { | |
int id; // task id | |
int burstTime; // time required to complete the task | |
int remainingTime; // remaining time to complete the task | |
struct task *next; // pointer to next task | |
} task_t; | |
// add a task to the linked list | |
void addTask(task_t **head, task_t **tail, int id, int burstTime) { | |
task_t *newTask = malloc(sizeof(task_t)); | |
newTask->id = id; | |
newTask->burstTime = burstTime; | |
newTask->remainingTime = burstTime; | |
newTask->next = NULL; | |
if (*head == NULL) { | |
*head = newTask; | |
} else { | |
(*tail)->next = newTask; | |
} | |
*tail = newTask; | |
} | |
int main() { | |
// create linked list of tasks | |
task_t *head = NULL; | |
task_t *tail = NULL; | |
// add tasks to linked list | |
addTask(&head, &tail, 0, 10); | |
addTask(&head, &tail, 1, 5); | |
addTask(&head, &tail, 2, 8); | |
addTask(&head, &tail, 3, 12); | |
task_t *current = head; // current task | |
int elapsedTime = 0; // elapsed time since start of scheduling | |
while (1) { | |
current->remainingTime -= QUANTUM; // decrement remaining time by time slice | |
elapsedTime += QUANTUM; // increment elapsed time | |
// if the task is completed | |
if (current->remainingTime <= 0) { | |
printf("Task %d completed.\n", current->id); | |
// if this is the last task, terminate scheduling | |
if (current->next == NULL) break; | |
// remove task from linked list | |
task_t *temp = current; | |
current = current->next; | |
free(temp); | |
} | |
// sleep for time slice | |
usleep(QUANTUM * 1000); | |
printf("Switched to task %d\n", current->id); | |
} | |
printf("Total elapsed time: %d milliseconds\n", elapsedTime); | |
// free linked list | |
while (head != NULL) { | |
task_t *temp = head; | |
head = head->next; | |
free(temp); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment