pingpong-semaphore-stress.c (2280B)
1 // PingPongOS - PingPong Operating System 2 // © Prof. Carlos A. Maziero, DINF UFPR 3 // Versão 2.1 -- 06/2026 4 5 // ATENÇÃO: ESTE ARQUIVO NÃO DEVE SER ALTERADO; 6 // ALTERAÇÕES SERÃO DESCARTADAS NA CORREÇÃO. 7 8 // Teste de semáforos (stress) 9 10 #include <assert.h> 11 #include "lib/pplibc.h" 12 #include "syscall.h" 13 14 #define NUMTASKS 64 15 #define NUMSTEPS 1000000 16 17 struct task_t *task[NUMTASKS]; 18 int s; 19 static int soma = 0; 20 21 // corpo das tarefas 22 void body() 23 { 24 int status; 25 26 for (int i = 0; i < NUMSTEPS; i++) 27 { 28 // incrementa contador (seção crítica) 29 status = sem_down(s); 30 if (status == ERROR) 31 break; 32 33 soma += 1; 34 35 status = sem_up(s); 36 if (status == ERROR) 37 break; 38 } 39 40 task_exit(NOERROR); 41 } 42 43 // corpo da tarefa principal 44 void user_main(void *arg) 45 { 46 int status, id; 47 char *name; 48 49 name = task_name(NULL); 50 id = task_id(NULL); 51 printk("%5u ms: %s (id %d): inicio\n", time(), name, id); 52 53 // inicia semáforo em 0 (bloqueado) 54 s = sem_create(0); 55 assert(s >= 0); 56 57 printk("%d tarefas somando %d vezes cada, aguarde...\n", 58 NUMTASKS, NUMSTEPS); 59 60 // cria tarefas 61 for (int i = 0; i < NUMTASKS; i++) 62 { 63 task[i] = task_create(NULL, body, "Task"); 64 assert(task[i]); 65 } 66 67 // espera um pouco para liberar o semáforo; isso faz com que todas 68 // as tarefas tenham sido criadas e possam competir pelo semáforo 69 // em pé de igualdade. 70 task_sleep(100); 71 status = sem_up(s); 72 assert(status == NOERROR); 73 74 // aguarda as tarefas encerrarem 75 for (int i = 0; i < NUMTASKS; i++) 76 { 77 status = task_wait(task[i]); 78 assert(status == NOERROR); 79 } 80 81 // verifica se a soma está correta 82 if (soma == (NUMTASKS * NUMSTEPS)) 83 printk("A soma deu %d, valor correto!\n", soma); 84 else 85 printk("A soma deu %d, mas deveria dar %d!\n", 86 soma, NUMTASKS * NUMSTEPS); 87 88 // destrói o semáforo 89 status = sem_destroy(s); 90 assert(status == NOERROR); 91 92 // destrói as tarefas 93 for (int i = 0; i < NUMTASKS; i++) 94 { 95 status = task_destroy(task[i]); 96 assert(status == NOERROR); 97 } 98 99 printk("%5u ms: %s fim\n", time(), name); 100 101 task_exit(NOERROR); 102 }