diofanto33

sem.c

Sep 28th, 2026
27
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.99 KB | None | 0 0
  1. #include "types.h"
  2. #include "param.h"
  3. #include "memlayout.h"
  4. #include "riscv.h"
  5. #include "spinlock.h"
  6. #include "proc.h"
  7. #include "defs.h"
  8.  
  9. // longitud del arreglo dentro del espacio de kernel
  10. #define NSEM 65
  11.  
  12. // tope maximo del contador de semaforo
  13. #define SEM_VALUE_MAX 1000000
  14.  
  15. struct sem {
  16.     int used;                 // 1 = abierto, 0 = cerrado
  17.     int value;                // contador
  18.     struct spinlock lock;
  19. };
  20.  
  21. // arreglo dentro del espacio de kernel, arreglo global
  22. struct sem sems[NSEM];
  23.  
  24. // inicializamos el arreglo de semaforos
  25. void
  26. seminit(void)
  27. {
  28.     for(int i = 0; i < NSEM; i = i+1)
  29.     {
  30.         initlock(&sems[i].lock, "sem");
  31.         sems[i].used = 0;
  32.         sems[i].value = 0;
  33.     }
  34. }
  35.  
  36.  
  37. /*  sem_up(sem): incrementa el contador y despierta a los que esperan.
  38.  *  Exito: retorna sem > 0
  39.  *  Error: retorna 0
  40.  *
  41.  */
  42. int
  43. sem_up(int sem)
  44. {
  45.     // variable de retorno
  46.     int result = 0;
  47.  
  48.     // fuera de rango
  49.     if(sem <= 0 || sem >= NSEM)
  50.     {
  51.         result = 0;
  52.     }
  53.     else
  54.     {
  55.         // apuntamos al semaforo en cuestion
  56.         struct sem *s = &sems[sem];
  57.         // bloqueamos el semaforo, exclusion mutua
  58.         acquire(&s->lock);
  59.  
  60.         // no estaba abierto o el contador se paso
  61.         if(!s->used || s->value >= SEM_VALUE_MAX)
  62.         {  
  63.             // liberamos el lock
  64.             release(&s->lock);
  65.             result = 0;
  66.         }
  67.         else // luz verde
  68.         {
  69.             // incrementamos el contador
  70.             s->value = s->value + 1;
  71.  
  72.             // lanza el proceso que hubiera llamado a sleep() antes
  73.             wakeup(s);
  74.  
  75.             // liberamos el lock
  76.             release(&s->lock);
  77.             // exito: devolvemos el id del semaforo (sem > 0)
  78.             result = sem;
  79.         }
  80.     }
  81.     return result;
  82. }
  83.  
  84. int
  85. sem_open(int sem, int value)  
  86. {
  87.   return 0;
  88. }
  89.  
  90. int
  91. sem_close(int sem)            
  92. {
  93.   return 0;
  94. }
  95.  
  96. int
  97. sem_down(int sem)              
  98. {
  99.   return 0;
  100. }
Advertisement
Add Comment
Please, Sign In to add comment