Advertisement
Guest User

Untitled

a guest
Nov 23rd, 2017
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.80 KB | None | 0 0
  1. / Compile as: gcc store_solution.c -lpthread -D_REENTRANT -Wall -o store
  2.  
  3. #include <stdlib.h>
  4. #include <stdio.h>
  5. #include <pthread.h>
  6. #include <semaphore.h>
  7. #include <unistd.h>
  8.  
  9. #define N_REQUESTS 100
  10. #define MAX_THREADS 4
  11. #define N_CLIENTS 10
  12.  
  13. typedef struct request{
  14. int value;
  15. int client;
  16. } request;
  17.  
  18. request requests[N_REQUESTS];
  19. int total_daily_requests=0;
  20.  
  21. int pos=0; // position in array
  22.  
  23. // threads id
  24. pthread_t my_thread[N_CLIENTS];
  25. int ids[N_CLIENTS]; // saves id from client threads
  26.  
  27. // sync resources
  28. pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
  29. sem_t threads_limit;
  30.  
  31.  
  32. void *generate_requests(void* id_ptr) {
  33. int id = *((int *)id_ptr);
  34. int new_request;
  35.  
  36. while(1){
  37. // the maximum threads working at the same time is MAX_THREADS
  38. // control the access to the 'pos' variable
  39.  
  40. /*insert code here*/
  41. pthread_mutex_lock(&mutex);
  42.  
  43. if(pos==N_REQUESTS){
  44. // exit thread
  45.  
  46. /*insert code here*/
  47. pthread_exit(NULL);
  48.  
  49. }
  50. new_request=rand()%100+1;
  51. requests[pos].value=new_request;
  52. requests[pos].client=id;
  53. pos++;
  54.  
  55. /*insert code here*/
  56.  
  57. printf("New request of %d products was generated by thread %d\n",new_request,id);
  58. usleep(10); //waits 10 us
  59. pthread_mutex_unlock(&mutex);
  60. }
  61. }
  62.  
  63. int main(void) {
  64. int i;
  65. sem_init(&threads_limit,0,MAX_THREADS);
  66.  
  67. // create threads client
  68.  
  69. /*insert code here*/
  70. for(int i =0;i<N_CLIENTS;i++){
  71. pthread_create(&my_thread[i], NULL, generate_requests, &ids[i]);
  72. }
  73.  
  74.  
  75. // wait until all threads client finish
  76.  
  77. /*insert code here*/
  78. for(int i =0;i<N_CLIENTS;i++){
  79. pthread_join(my_thread[i], NULL);
  80. }
  81.  
  82. // count items sold
  83. for(i=0;i<N_REQUESTS;i++) total_daily_requests+=requests[i].value;
  84. printf("Total items sold = %d\n",total_daily_requests);
  85. exit(0);
  86. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement