]> wirehaze git hosting - ppos.git/blob - ppos/test/pingpong-semaphore-stress.c

wirehaze git hosting

tasks implementation (ongoing)
[ppos.git] / ppos / test / pingpong-semaphore-stress.c
1 // PingPongOS - PingPong Operating System
2 // Prof. Carlos A. Maziero, DINF UFPR
3 // Versão 2.0 -- Junho de 2025
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/libc.h"
12 #include "ppos.h"
13
14 #define NUMTASKS 64
15 #define NUMSTEPS 1000000
16
17 static struct task_t *task[NUMTASKS];
18 static struct semaphore_t *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(0);
41 }
42
43 // corpo da tarefa principal
44 void user_main(void *arg)
45 {
46 int status;
47
48 printf("user: inicio\n");
49
50 // inicia semáforo em 0 (bloqueado)
51 s = sem_create(0);
52 assert(s);
53
54 printf("%d tarefas somando %d vezes cada, aguarde...\n",
55 NUMTASKS, NUMSTEPS);
56
57 // cria tarefas
58 for (int i = 0; i < NUMTASKS; i++)
59 {
60 task[i] = task_create(NULL, body, "Task");
61 assert(task[i]);
62 }
63
64 // espera um pouco para liberar o semáforo; isso faz com que todas
65 // as tarefas tenham sido criadas e possam competir pelo semáforo
66 // em pé de igualdade.
67 task_sleep(100);
68 status = sem_up(s);
69 assert(status == NOERROR);
70
71 // aguarda as tarefas encerrarem
72 for (int i = 0; i < NUMTASKS; i++)
73 {
74 status = task_wait(task[i]);
75 assert(status == NOERROR);
76 }
77
78 // destroi o semáforo
79 status = sem_destroy(s);
80 assert(status == NOERROR);
81
82 // verifica se a soma está correta
83 if (soma == (NUMTASKS * NUMSTEPS))
84 printf("A soma deu %d, valor correto!\n", soma);
85 else
86 printf("A soma deu %d, mas deveria dar %d!\n",
87 soma, NUMTASKS * NUMSTEPS);
88
89 // destroi os descritores
90 for (int i = 0; i < NUMTASKS; i++)
91 {
92 status = task_destroy(task[i]);
93 assert(status == NOERROR);
94 }
95
96 printf("user: fim\n");
97
98 task_exit(0);
99 }