-
Notifications
You must be signed in to change notification settings - Fork 0
/
stock.c
115 lines (97 loc) · 2.48 KB
/
stock.c
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
110
111
112
113
114
115
/* Code from tuto http://franckh.developpez.com/tutoriels/posix/pthreads/ please do not copy check link for more infos */
/* I'm not the author of this code I just followed a very good tutorial from Franck Hecht on pthread */
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <string.h>
#define psleep(sec) sleep((sec))
#define INITIAL_STOCK 20
#define NB_CLIENTS 5
typedef struct
{
int stock;
pthread_t thread_store;
pthread_t thread_clients[NB_CLIENTS];
pthread_mutex_t mutex_stock;
pthread_cond_t cond_stock;
pthread_cond_t cond_clients;
}
store_t;
static store_t store =
{
.stock = INITIAL_STOCK,
.mutex_stock = PTHREAD_MUTEX_INITIALIZER,
.cond_stock = PTHREAD_COND_INITIALIZER,
.cond_clients = PTHREAD_COND_INITIALIZER,
};
static int get_random(int max)
{
double val;
val = (double) max * rand();
val = val / (RAND_MAX + 1.0);
return ((int) val);
}
/* store thread */
static void *fn_store (void *p_data)
{
while (1)
{
/* debut de la zone protegee */
pthread_mutex_lock(&store.mutex_stock);
pthread_cond_wait(&store.cond_stock, &store.mutex_stock);
store.stock = INITIAL_STOCK;
printf("Remplissage du stock de %d articles !\n", store.stock);
/* fin de la zone protege */
pthread_cond_signal(&store.cond_clients);
pthread_mutex_unlock(&store.mutex_stock);
}
return NULL;
}
/* clients thread */
static void *fn_clients(void *p_data)
{
int nb = (int)p_data;
while (1)
{
int val = get_random(6);
psleep(get_random(3));
pthread_mutex_lock(&store.mutex_stock);
if (val > store.stock)
{
pthread_cond_signal(&store.cond_stock);
pthread_cond_wait(&store.cond_clients, &store.mutex_stock);
}
store.stock = store.stock - val;
printf("Client %d prend %d du stock, reste, %d en stock!\n",
nb, val, store.stock);
pthread_mutex_unlock(&store.mutex_stock);
}
return NULL;
}
int main (void)
{
int i = 0;
int ret = 0;
/* create store thread */
printf("Creation du thread magasin!\n");
ret = pthread_create(&store.thread_store, NULL, fn_store, NULL);
if (!ret)
{
printf("Creation des threads clients !\n");
for (i = 0; i < NB_CLIENTS; i++)
{
ret = pthread_create(&store.thread_clients[i], NULL, fn_clients, (void *)i);
if (ret)
fprintf(stderr, "%s", strerror(ret));
}
}
else
fprintf(stderr, "%s", strerror(ret));
/* wait for thread to finish */
i = 0;
for (i = 0; i < NB_CLIENTS; i++)
pthread_join(store.thread_clients[i], NULL);
pthread_join(store.thread_store, NULL);
return (EXIT_SUCCESS);
}