Repository navigation
Expand file tree
/
Copy pathmain.c
More file actions
109 lines (84 loc) · 2.7 KB
/
Copy pathmain.c
File metadata and controls
109 lines (84 loc) · 2.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <time.h>
#include "fila.h"
#define MAX_CLIENTES 20
#define NUM_ATENDENTES 3
Fila fila;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
pthread_mutex_t print_mutex = PTHREAD_MUTEX_INITIALIZER;
bool fim_producao = false;
int cliente_id_global = 1;
void* gerarClientes(void* arg) {
for (int i = 0; i < MAX_CLIENTES; i++) {
sleep(rand() % 3 + 1);
Cliente c;
c.id = cliente_id_global++;
c.tempo_atendimento = rand() % 4 + 2;
pthread_mutex_lock(&fila.mutex);
while (isFull(&fila)) {
pthread_mutex_unlock(&fila.mutex);
sleep(1);
pthread_mutex_lock(&fila.mutex);
}
enqueue(&fila, c);
pthread_mutex_lock(&print_mutex);
printf("Cliente %d chegou e entrou na fila (atendimento: %d seg)\n", c.id, c.tempo_atendimento);
pthread_mutex_unlock(&print_mutex);
pthread_mutex_unlock(&fila.mutex);
pthread_cond_signal(&cond);
}
pthread_mutex_lock(&fila.mutex);
fim_producao = true;
pthread_mutex_unlock(&fila.mutex);
pthread_cond_broadcast(&cond);
return NULL;
}
void* atendente(void* arg) {
int id = *(int*)arg;
int atendidos = 0;
while (1) {
pthread_mutex_lock(&fila.mutex);
while (isEmpty(&fila) && !fim_producao) {
pthread_cond_wait(&cond, &fila.mutex);
}
if (isEmpty(&fila) && fim_producao) {
pthread_mutex_unlock(&fila.mutex);
break;
}
Cliente cliente;
dequeue(&fila, &cliente);
pthread_mutex_unlock(&fila.mutex);
pthread_mutex_lock(&print_mutex);
printf("[Atendente %d] Atendendo cliente %d por %d segundos\n", id, cliente.id, cliente.tempo_atendimento);
pthread_mutex_unlock(&print_mutex);
sleep(cliente.tempo_atendimento);
atendidos++;
}
pthread_mutex_lock(&print_mutex);
printf("[Atendente %d] Finalizando. Total atendidos: %d\n", id, atendidos);
pthread_mutex_unlock(&print_mutex);
return NULL;
}
int main() {
srand(time(NULL));
criarFila(&fila);
pthread_t thread_produtor;
pthread_t atendentes[NUM_ATENDENTES];
int ids[NUM_ATENDENTES];
pthread_create(&thread_produtor, NULL, gerarClientes, NULL);
for (int i = 0; i < NUM_ATENDENTES; i++) {
ids[i] = i + 1;
pthread_create(&atendentes[i], NULL, atendente, &ids[i]);
}
pthread_join(thread_produtor, NULL);
for (int i = 0; i < NUM_ATENDENTES; i++) {
pthread_join(atendentes[i], NULL);
}
destroyFila(&fila);
pthread_mutex_destroy(&print_mutex);
pthread_cond_destroy(&cond);
return 0;
}