Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <signal.h>
- #include <ucontext.h>
- #include <stdlib.h>
- #include <stdio.h>
- #define MAX_TASKS 10
- enum TaskState {READY, RUNNING, BLOCKED};
- struct TaskControlBlock {
- int task_id;
- TaskState state;
- ucontext_t context;
- };
- struct TaskControlBlock tasks[MAX_TASKS];
- int current_task = 0;
- int num_tasks = 0;
- void scheduler(int signum) {
- // Switch to the next task
- int next_task = (current_task + 1) % num_tasks;
- while (tasks[next_task].state != READY) {
- next_task = (next_task + 1) % num_tasks;
- }
- if (next_task != current_task) {
- tasks[current_task].state = READY;
- tasks[next_task].state = RUNNING;
- current_task = next_task;
- swapcontext(&tasks[current_task].context, &tasks[next_task].context);
- }
- }
- void initlibrary() {
- // Initialize the signal handler for the timer
- struct sigaction sa;
- sa.sa_handler = scheduler;
- sigemptyset(&sa.sa_mask);
- sa.sa_flags = 0;
- sigaction(SIGALRM, &sa, NULL);
- // Set up the timer to generate a signal every 10ms
- struct itimerval timer;
- timer.it_interval.tv_sec = 0;
- timer.it_interval.tv_usec = 10000;
- timer.it_value = timer.it_interval;
- setitimer(ITIMER_REAL, &timer, NULL);
- }
- int create_task(void *(*start_routine)(void *)) {
- if (num_tasks >= MAX_TASKS) {
- return 1; // Error: maximum number of tasks reached
- }
- // Create a context for the task
- ucontext_t context;
- getcontext(&context);
- context.uc_link = NULL;
- context.uc_stack.ss_sp = malloc(SIGSTKSZ);
- context.uc_stack.ss_size = SIGSTKSZ;
- context.uc_stack.ss_flags = 0;
- makecontext(&context, (void (*)()) start_routine, 0);
- // Create a control block for the task
- tasks[num_tasks].task_id = num_tasks;
- tasks[num_tasks].state = READY;
- tasks[num_tasks].context = context;
- num_tasks++;
- return 0;
- }
- void *task1(void *arg) {
- while (1) {
- printf("+");
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement