1. #include <stdio.h>
  2. #include <pthread.h>
  3. #include <semaphore.h>
  4. #include <unistd.h>
  5. #include <stdlib.h>
  6. #include <assert.h>
  7.  
  8. int n = 0; /* nb d'éléments dans le stockage */
  9. int stock[5]; /* stockage */
  10.  
  11. int valeur(){
  12. return n;
  13. }
  14.  
  15. void ajoute(int x){
  16. assert(n < 5);
  17. stock[n] = x;
  18. n += 1;
  19. }
  20.  
  21. int retire(){
  22. assert(n > 0);
  23. n -= 1;
  24. return stock[n];
  25. }
  26.  
  27. void* producteur(void* args){
  28. char* nom = (char*) args;
  29. for (int i = 0; i < 10; i += 1) {
  30. sleep((rand() % 100) * 0.01);
  31. printf("procucteur %s ajoute %d\n", nom, i);
  32. ajoute(i);
  33. }
  34. return NULL;
  35. }
  36.  
  37. void* consommateur(void* args){
  38. char* nom = (char*) args;
  39. for (int i = 0; i < 15; i += 1) {
  40. sleep((rand() % 100) * 0.01);
  41. int x = retire();
  42. printf("consommateur %s retire %d\n", nom, x);
  43. }
  44. return NULL;
  45. }
  46.  
  47. int main() {
  48. srand(time(NULL));
  49. pthread_t p1, p2, p3;
  50. pthread_t c1, c2;
  51. pthread_create(&p1, NULL, producteur, "A");
  52. pthread_create(&p2, NULL, producteur, "B");
  53. pthread_create(&p3, NULL, producteur, "C");
  54. pthread_create(&c1, NULL, consommateur, "D");
  55. pthread_create(&c2, NULL, consommateur, "E");
  56. pthread_join(p1, NULL);
  57. pthread_join(p2, NULL);
  58. pthread_join(p3, NULL);
  59. pthread_join(c1, NULL);
  60. pthread_join(c2, NULL);
  61. return 0;
  62. }