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

wirehaze git hosting

add ppos/
[ppos.git] / ppos / test / pingpong-semaphore.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 (leve)
9
10 #include <assert.h>
11 #include "lib/libc.h"
12 #include "ppos.h"
13
14 static struct task_t *a1, *a2, *b1, *b2;
15 static struct semaphore_t *s1, *s2;
16
17 // corpo da tarefa A
18 void body_a(void *arg)
19 {
20 int status;
21
22 for (int i = 0; i < 5; i++)
23 {
24 status = sem_down(s1);
25 if (status == ERROR)
26 break;
27
28 printf("%5d ms: %s zig (%d)\n", systime(), (char *)arg, i);
29 task_sleep(1000);
30
31 status = sem_up(s2);
32 if (status == ERROR)
33 break;
34 }
35 task_exit(0);
36 }
37
38 // corpo da tarefa B
39 void body_b(void *arg)
40 {
41 int status;
42
43 for (int i = 0; i < 5; i++)
44 {
45 status = sem_down(s2);
46 if (status == ERROR)
47 break;
48
49 printf("%5d ms: %s zag (%d)\n", systime(), (char *)arg, i);
50 task_sleep(1000);
51
52 status = sem_up(s1);
53 if (status == ERROR)
54 break;
55 }
56 task_exit(0);
57 }
58
59 // corpo da tarefa principal
60 void user_main(void *arg)
61 {
62 int status;
63
64 printf("user: inicio\n");
65
66 // inicia semáforos
67 s1 = sem_create(1);
68 assert(s1);
69 s2 = sem_create(0);
70 assert(s2);
71
72 // cria tarefas
73 a1 = task_create("a1", body_a, "A1");
74 assert(a1);
75 a2 = task_create("a2", body_a, "\tA2");
76 assert(a2);
77 b1 = task_create("b1", body_b, "\t\t\tB1");
78 assert(b1);
79 b2 = task_create("b2", body_b, "\t\t\t\tB2");
80 assert(b2);
81
82 // aguarda a1 encerrar
83 status = task_wait(a1);
84 assert(status == NOERROR);
85
86 // destroi semáforos
87 status = sem_destroy(s1);
88 assert(status == NOERROR);
89 status = sem_destroy(s2);
90 assert(status == NOERROR);
91
92 // aguarda a2, b1 e b2 encerrarem
93 status = task_wait(a2);
94 assert(status == NOERROR);
95 status = task_wait(b1);
96 assert(status == NOERROR);
97 status = task_wait(b2);
98 assert(status == NOERROR);
99
100 // destroi os descritores das tarefas
101 status = task_destroy(a1);
102 assert(status == NOERROR);
103 status = task_destroy(a2);
104 assert(status == NOERROR);
105 status = task_destroy(b1);
106 assert(status == NOERROR);
107 status = task_destroy(b2);
108 assert(status == NOERROR);
109
110 printf("user: fim\n");
111
112 task_exit(0);
113 }