home *** CD-ROM | disk | FTP | other *** search
/ Virtual Reality Zone / VRZONE.ISO / mac / PC / REND386 / DEVEL5 / TASKS.C < prev    next >
C/C++ Source or Header  |  1992-09-06  |  2KB  |  81 lines

  1. /* Very simple, non-preemptive, multitasking system
  2.    with round-robin scheduling */
  3.  
  4. /* Written by Bernie Roehl, June 1992 */
  5.  
  6. /* Copyright 1992 by Dave Stampe and Bernie Roehl.
  7.    May be freely used to write software for release into the public domain;
  8.    all commercial endeavours MUST contact Bernie Roehl and Dave Stampe
  9.    for permission to incorporate any part of this software into their
  10.    products!
  11.  */
  12.  
  13. #include <stdio.h>
  14. #include <alloc.h>  /* malloc() */
  15. #include "../include/rend386.h"  /* for current_time() */
  16.  
  17. typedef struct _task TASK;
  18.  
  19. struct _task {
  20.     void (*fn)(int cmd, void *msg, long now, long period);
  21.     void *data;
  22.     long period, lastran, wakeup;
  23.     TASK *next;
  24. };
  25.  
  26. static TASK *current_task = NULL;
  27.  
  28. TASK *get_current_task()
  29. {
  30.     return current_task;
  31. }
  32.  
  33. TASK *add_task(TASK **tasklist, void (*fn)(), long period, void *param)
  34. {
  35.     TASK *t;
  36.     if ((t = malloc(sizeof(TASK))) == NULL) return NULL;
  37.     t->fn = fn; 
  38.     t->data = NULL; 
  39.     t->period = period;
  40.     t->lastran = 0L; 
  41.     t->wakeup = current_time();
  42.     t->next = *tasklist;
  43.     current_task = *tasklist = t;
  44.     if (fn) (*fn)(0, param, current_time(), period); /* initialize */
  45.     return t;
  46. }
  47.  
  48. void del_task(TASK **tasklist, TASK *tsk)
  49. {
  50.     TASK *t;
  51.     if (tsk == NULL) return;
  52.     if (tsk == *tasklist)
  53.         *tasklist = tsk->next;
  54.     else
  55.         for (t = *tasklist; t; t = t->next)
  56.         if (t->next == tsk) {
  57.             t->next = tsk->next;
  58.             break;
  59.         }
  60.     free(tsk);
  61. }
  62.  
  63. void *find_task_data(TASK *task)
  64. {
  65.     return &task->data;
  66. }
  67.  
  68. void run_tasks(TASK *tasklist)
  69. {
  70.     long now;
  71.     now = current_time();
  72.     for (current_task = tasklist; current_task; current_task = current_task->next) {
  73.         if (current_task->fn && (now >= current_task->wakeup)) {
  74.             current_task->wakeup = now + current_task->period;
  75.             current_task->fn(1, NULL, now, current_task->period);
  76.             current_task->lastran = now;
  77.         }
  78.     }
  79. }
  80.  
  81.