pingpong-semaphore.c (2625B)
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 (leve) 9 10 #include <assert.h> 11 #include "lib/pplibc.h" 12 #include "syscall.h" 13 14 struct task_t *a1, *a2, *b1, *b2; // descritores de tarefas 15 int s1, s2; // descritores de semáforos 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 task_exit(1); 27 28 printk("%5u ms: %s zig (%d)\n", time(), (char *)arg, i); 29 task_sleep(1000); 30 31 status = sem_up(s2); 32 if (status == ERROR) 33 task_exit(2); 34 } 35 36 task_exit(NOERROR); 37 } 38 39 // corpo da tarefa B 40 void body_b(void *arg) 41 { 42 int status; 43 44 for (int i = 0; i < 5; i++) 45 { 46 status = sem_down(s2); 47 if (status == ERROR) 48 task_exit(1); 49 50 printk("%5u ms: %s zag (%d)\n", time(), (char *)arg, i); 51 task_sleep(1000); 52 53 status = sem_up(s1); 54 if (status == ERROR) 55 task_exit(2); 56 } 57 task_exit(NOERROR); 58 } 59 60 // corpo da tarefa principal 61 void user_main(void *arg) 62 { 63 int status, id; 64 char *name; 65 66 name = task_name(NULL); 67 id = task_id(NULL); 68 printk("%5u ms: %s (id %d): inicio\n", time(), name, id); 69 70 // inicia semáforos 71 s1 = sem_create(1); 72 assert(s1 >= 0); 73 s2 = sem_create(0); 74 assert(s2 >= 0); 75 76 // cria tarefas 77 a1 = task_create("a1", body_a, "A1"); 78 assert(a1); 79 a2 = task_create("a2", body_a, "\tA2"); 80 assert(a2); 81 b1 = task_create("b1", body_b, "\t\t\tB1"); 82 assert(b1); 83 b2 = task_create("b2", body_b, "\t\t\t\tB2"); 84 assert(b2); 85 86 // aguarda a1 encerrar sem erro 87 status = task_wait(a1); 88 assert(status == NOERROR); 89 90 // destrói semáforos 91 status = sem_destroy(s1); 92 assert(status == NOERROR); 93 status = sem_destroy(s2); 94 assert(status == NOERROR); 95 96 // aguarda a2, b1 e b2 encerrarem com erro 97 status = task_wait(a2); 98 assert(status != NOERROR); 99 status = task_wait(b1); 100 assert(status != NOERROR); 101 status = task_wait(b2); 102 assert(status != NOERROR); 103 104 // destrói as tarefas 105 status = task_destroy(a1); 106 assert(status == NOERROR); 107 status = task_destroy(a2); 108 assert(status == NOERROR); 109 status = task_destroy(b1); 110 assert(status == NOERROR); 111 status = task_destroy(b2); 112 assert(status == NOERROR); 113 114 printk("%5u ms: %s fim\n", time(), name); 115 116 task_exit(NOERROR); 117 }