@@ -1,21 +1,39 @@
|
|
1 |
// Copyright 2021 Jeisson Hidalgo-Cespedes <jeisson.hidalgo@ucr.ac.cr> CC-BY-4
|
2 |
|
3 |
#include <stdio.h>
|
4 |
|
5 |
#include "common.h"
|
6 |
#include "producer.h"
|
7 |
|
8 |
void* produce(void* data) {
|
9 |
// const private_data_t* private_data = (private_data_t*)data;
|
10 |
simulation_t* simulation = (simulation_t*)data;
|
11 |
|
12 |
-
while (
|
13 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
14 |
usleep(1000 * random_between(simulation->producer_min_delay
|
15 |
, simulation->producer_max_delay));
|
16 |
queue_enqueue(&simulation->queue, my_unit);
|
17 |
printf("Produced %zu\n", my_unit);
|
|
|
|
|
|
|
18 |
}
|
19 |
|
20 |
return NULL;
|
21 |
}
|
1 |
// Copyright 2021 Jeisson Hidalgo-Cespedes <jeisson.hidalgo@ucr.ac.cr> CC-BY-4
|
2 |
|
3 |
#include <stdio.h>
|
4 |
|
5 |
#include "common.h"
|
6 |
#include "producer.h"
|
7 |
|
8 |
void* produce(void* data) {
|
9 |
// const private_data_t* private_data = (private_data_t*)data;
|
10 |
simulation_t* simulation = (simulation_t*)data;
|
11 |
|
12 |
+
while (true) {
|
13 |
+
// declare my_unit := 0
|
14 |
+
size_t my_unit = 0;
|
15 |
+
// lock(can_access_next_unit)
|
16 |
+
pthread_mutex_lock(&simulation->can_access_next_unit);
|
17 |
+
// If is there pending work, take a unit for producing
|
18 |
+
if (simulation->next_unit < simulation->unit_count) {
|
19 |
+
my_unit = ++simulation->next_unit;
|
20 |
+
} else {
|
21 |
+
// unlock(can_access_next_unit)
|
22 |
+
pthread_mutex_unlock(&simulation->can_access_next_unit);
|
23 |
+
// break while
|
24 |
+
break;
|
25 |
+
}
|
26 |
+
// unlock(can_access_next_unit)
|
27 |
+
pthread_mutex_unlock(&simulation->can_access_next_unit);
|
28 |
+
|
29 |
usleep(1000 * random_between(simulation->producer_min_delay
|
30 |
, simulation->producer_max_delay));
|
31 |
queue_enqueue(&simulation->queue, my_unit);
|
32 |
printf("Produced %zu\n", my_unit);
|
33 |
+
|
34 |
+
// signal(can_consume)
|
35 |
+
sem_post(&simulation->can_consume);
|
36 |
}
|
37 |
|
38 |
return NULL;
|
39 |
}
|