Advertisement
moldovexc

helpme

Mar 5th, 2023 (edited)
159
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.99 KB | None | 0 0
  1. #include <signal.h>
  2. #include <ucontext.h>
  3. #include <stdlib.h>
  4. #include <stdio.h>
  5.  
  6. #define MAX_TASKS 10
  7.  
  8. enum TaskState {READY, RUNNING, BLOCKED};
  9.  
  10. struct TaskControlBlock {
  11.     int task_id;
  12.     TaskState state;
  13.     ucontext_t context;
  14. };
  15.  
  16. struct TaskControlBlock tasks[MAX_TASKS];
  17. int current_task = 0;
  18. int num_tasks = 0;
  19.  
  20. void scheduler(int signum) {
  21.     // Switch to the next task
  22.     int next_task = (current_task + 1) % num_tasks;
  23.     while (tasks[next_task].state != READY) {
  24.         next_task = (next_task + 1) % num_tasks;
  25.     }
  26.     if (next_task != current_task) {
  27.         tasks[current_task].state = READY;
  28.         tasks[next_task].state = RUNNING;
  29.         current_task = next_task;
  30.         swapcontext(&tasks[current_task].context, &tasks[next_task].context);
  31.     }
  32. }
  33.  
  34. void initlibrary() {
  35.     // Initialize the signal handler for the timer
  36.     struct sigaction sa;
  37.     sa.sa_handler = scheduler;
  38.     sigemptyset(&sa.sa_mask);
  39.     sa.sa_flags = 0;
  40.     sigaction(SIGALRM, &sa, NULL);
  41.    
  42.     // Set up the timer to generate a signal every 10ms
  43.     struct itimerval timer;
  44.     timer.it_interval.tv_sec = 0;
  45.     timer.it_interval.tv_usec = 10000;
  46.     timer.it_value = timer.it_interval;
  47.     setitimer(ITIMER_REAL, &timer, NULL);
  48. }
  49.  
  50. int create_task(void *(*start_routine)(void *)) {
  51.     if (num_tasks >= MAX_TASKS) {
  52.         return 1; // Error: maximum number of tasks reached
  53.     }
  54.    
  55.     // Create a context for the task
  56.     ucontext_t context;
  57.     getcontext(&context);
  58.     context.uc_link = NULL;
  59.     context.uc_stack.ss_sp = malloc(SIGSTKSZ);
  60.     context.uc_stack.ss_size = SIGSTKSZ;
  61.     context.uc_stack.ss_flags = 0;
  62.     makecontext(&context, (void (*)()) start_routine, 0);
  63.    
  64.     // Create a control block for the task
  65.     tasks[num_tasks].task_id = num_tasks;
  66.     tasks[num_tasks].state = READY;
  67.     tasks[num_tasks].context = context;
  68.     num_tasks++;
  69.    
  70.     return 0;
  71. }
  72.  
  73. void *task1(void *arg) {
  74.     while (1) {
  75.         printf("+");
  76.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement