- #include <stdio.h>
- #include <pthread.h>
- #include <semaphore.h>
- #include <unistd.h>
- #include <stdlib.h>
- #include <assert.h>
-
- int n = 0; /* nb d'éléments dans le stockage */
- int stock[5]; /* stockage */
-
- int valeur(){
- return n;
- }
-
- void ajoute(int x){
- assert(n < 5);
- stock[n] = x;
- n += 1;
- }
-
- int retire(){
- assert(n > 0);
- n -= 1;
- return stock[n];
- }
-
- void* producteur(void* args){
- char* nom = (char*) args;
- for (int i = 0; i < 10; i += 1) {
- sleep((rand() % 100) * 0.01);
- printf("procucteur %s ajoute %d\n", nom, i);
- ajoute(i);
- }
- return NULL;
- }
-
- void* consommateur(void* args){
- char* nom = (char*) args;
- for (int i = 0; i < 15; i += 1) {
- sleep((rand() % 100) * 0.01);
- int x = retire();
- printf("consommateur %s retire %d\n", nom, x);
- }
- return NULL;
- }
-
- int main() {
- srand(time(NULL));
- pthread_t p1, p2, p3;
- pthread_t c1, c2;
- pthread_create(&p1, NULL, producteur, "A");
- pthread_create(&p2, NULL, producteur, "B");
- pthread_create(&p3, NULL, producteur, "C");
- pthread_create(&c1, NULL, consommateur, "D");
- pthread_create(&c2, NULL, consommateur, "E");
- pthread_join(p1, NULL);
- pthread_join(p2, NULL);
- pthread_join(p3, NULL);
- pthread_join(c1, NULL);
- pthread_join(c2, NULL);
- return 0;
- }