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 116 117 118 119 120 121 122 123 124 125 126 127 128 129
| #include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#ifdef __WIN32__
# include <windows.h>
# define psleep(sec) Sleep ((sec) * 1000)
#else
# include <unistd.h>
# define psleep(sec) sleep ((sec))
#endif
#define INITIAL_STOCK 20
#define NB_CLIENTS 5
/* Struct informations of threads clients and magasin. */
typedef struct
{
int stock;
pthread_t thread_store;
pthread_t thread_clients [NB_CLIENTS];
}
store_t;
static store_t store =
{
.stock = INITIAL_STOCK,
};
/* Function get a number between 0 and max. */
static int get_random (int max)
{
double val;
val = (double) max * rand ();
val = val / (RAND_MAX + 1.0);
return ((int) val);
}
/* Function thread magasin. */
static void * fn_store (void * p_data)
{
while (1)
{
if (store.stock <= 0)
{
store.stock = INITIAL_STOCK;
printf ("Remplissage du stock de %d articles !\n", store.stock);
fflush(stdout);
}
}
return NULL;
}
/* Function thread clients. */
static void * fn_clients (void * p_data)
{
int nb = (int) p_data;
while (1)
{
int val = get_random (6);
psleep (get_random (3));
store.stock = store.stock - val;
printf (
"Client %d prend %d du stock, reste %d en stock !\n",
nb, val, store.stock
);
fflush(stdout);
}
return NULL;
}
int main (void)
{
int i = 0;
int ret = 0;
/* Creation threads: magasin */
printf ("Creation du thread du magasin !\n");
ret = pthread_create (
& store.thread_store, NULL,
fn_store, NULL
);
/* Creation threads: clients */
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 the end of threads. */
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;
} |
Partager