Skip to content

Instantly share code, notes, and snippets.

@oriapp
Created January 8, 2023 11:31
Show Gist options
  • Save oriapp/7cefcb9cdce4e747a2431d42df145bee to your computer and use it in GitHub Desktop.
Save oriapp/7cefcb9cdce4e747a2431d42df145bee to your computer and use it in GitHub Desktop.
(Scheduling Algorithm) Round Robin PoC for my Operating System (v.2)
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#define TIME_SLICE 5 // time slice for each task
// 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;
}
// remove a task from the linked list
void removeTask(task_t **head, task_t *task) {
task_t *prev = NULL;
task_t *current = *head;
while (current != NULL && current != task) {
prev = current;
current = current->next;
}
if (current == NULL) return; // task not found
if (prev == NULL) { // task is head
*head = current->next;
} else {
prev->next = current->next;
}
free(current);
}
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);
int elapsedTime = 0; // elapsed time since start of scheduling
while (head != NULL) {
task_t *current = head;
while (current != NULL) {
elapsedTime += TIME_SLICE; // increment elapsed time
current->remainingTime -= TIME_SLICE;
printf("Switching to task %d.\n", current->id);
if (current->remainingTime <= 0) {
printf("Task %d completed.\n", current->id);
task_t *next = current->next;
removeTask(&head, current);
current = next;
} else {
current = current->next;
}
}
}
printf("Total elapsed time: %d milliseconds\n", elapsedTime);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment