Advertisement
Guest User

Untitled

a guest
Nov 1st, 2014
158
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.66 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <semaphore.h>
  3. #include <pthread.h>
  4. #include <time.h>
  5. #include <stdlib.h>
  6.  
  7. sem_t read_s, write_s;
  8. int g_buffer[3] = {0,0,0};
  9. int w_counter = 0;
  10. int r_counter = 0;
  11.  
  12.  
  13. //val : 1<=random <= 100
  14. int randomize(){
  15. return rand()%100 + 1;
  16. }
  17.  
  18. void * construire_m(void* arg){
  19. int cpt = 0, val = 0;
  20. for(cpt = 0; cpt<30; cpt++){
  21.  
  22. //generation de la val random
  23. val = randomize();
  24. sem_wait(&write_s);
  25. //write
  26. g_buffer[w_counter] = val;
  27. printf("W: [%d] = %d\n", w_counter,g_buffer[w_counter] );
  28. sem_post(&read_s);
  29. w_counter = (w_counter +1) % 3;
  30. }
  31. pthread_exit(NULL);
  32.  
  33. }
  34.  
  35. void * consommer_m(void* arg){
  36. int cpt = 0;
  37. for(cpt = 0; cpt<30; cpt++){
  38. sem_wait(&read_s);
  39. //read
  40. printf("R: [%d] = %d\n", r_counter, g_buffer[r_counter]);
  41. sem_post(&write_s);
  42. r_counter = (r_counter +1) % 3;
  43. }
  44. pthread_exit(NULL);
  45. }
  46.  
  47.  
  48. int main(int argc, char *argv[])
  49. {
  50.  
  51. int iCtr = 0;
  52. pthread_t t_write, t_read;
  53.  
  54. printf("[+] Initialisation \n");
  55. //initialisation des semaphores
  56.  
  57. sem_init(&read_s , 0, 0);
  58. sem_init(&write_s, 0, 3);
  59.  
  60.  
  61. //initialisation du seed de rand
  62. srand(time(NULL));
  63.  
  64. printf("[+] Trace : \n");
  65. //creation des thread
  66. if(pthread_create(&t_write, NULL,construire_m, NULL))
  67. {
  68. printf("Impossible de créer le thread d'ecriture\n");
  69. exit(1);
  70. }
  71. if(pthread_create(&t_read, NULL,consommer_m, NULL))
  72. {
  73. printf("Impossible de créer le thread de lecture\n");
  74. exit(1);
  75. }
  76.  
  77. printf("[+] Threads created\n");
  78.  
  79. pthread_join(t_read,NULL);
  80. pthread_join(t_write,NULL);
  81.  
  82.  
  83.  
  84. //creation des thread
  85. return 0;
  86. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement