pthreads/prod_cons_unbound/{given → src}/consumer.c RENAMED
@@ -1,22 +1,38 @@
1
  // Copyright 2021 Jeisson Hidalgo-Cespedes <jeisson.hidalgo@ucr.ac.cr> CC-BY-4
2
 
3
  #include <stdbool.h>
4
  #include <stdio.h>
5
 
6
  #include "common.h"
7
  #include "consumer.h"
8
 
9
  void* consume(void* data) {
10
  simulation_t* simulation = (simulation_t*)data;
11
 
12
- while (simulation->consumed_count < simulation->unit_count) {
 
 
 
 
13
  ++simulation->consumed_count;
 
 
 
 
 
 
 
 
 
 
 
 
14
  size_t value = 0;
15
  queue_dequeue(&simulation->queue, &value);
16
  printf("\tConsuming %zu\n", value);
17
  usleep(1000 * random_between(simulation->consumer_min_delay
18
  , simulation->consumer_max_delay));
19
  }
20
 
21
  return NULL;
22
  }
1
  // Copyright 2021 Jeisson Hidalgo-Cespedes <jeisson.hidalgo@ucr.ac.cr> CC-BY-4
2
 
3
  #include <stdbool.h>
4
  #include <stdio.h>
5
 
6
  #include "common.h"
7
  #include "consumer.h"
8
 
9
  void* consume(void* data) {
10
  simulation_t* simulation = (simulation_t*)data;
11
 
12
+ while (true) {
13
+ // lock(can_access_consumed_count)
14
+ pthread_mutex_lock(&simulation->can_access_consumed_count);
15
+ if (simulation->consumed_count < simulation->unit_count) {
16
+ // Reserve the next product to me
17
  ++simulation->consumed_count;
18
+ } else {
19
+ // unlock(can_access_consumed_count)
20
+ pthread_mutex_unlock(&simulation->can_access_consumed_count);
21
+ // break while
22
+ break;
23
+ }
24
+ // unlock(can_access_consumed_count)
25
+ pthread_mutex_unlock(&simulation->can_access_consumed_count);
26
+
27
+ // wait(can_consume)
28
+ sem_wait(&simulation->can_consume);
29
+
30
  size_t value = 0;
31
  queue_dequeue(&simulation->queue, &value);
32
  printf("\tConsuming %zu\n", value);
33
  usleep(1000 * random_between(simulation->consumer_min_delay
34
  , simulation->consumer_max_delay));
35
  }
36
 
37
  return NULL;
38
  }