Advertisement
Guest User

Untitled

a guest
Jun 19th, 2018
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.37 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <unistd.h>
  4. #include <pthread.h>
  5. #include <time.h>
  6. #include <limits.h>
  7. #include <semaphore.h>
  8.  
  9. #include <sys/types.h>
  10. #include <sys/wait.h>
  11.  
  12. #define THREADS 8
  13.  
  14. int aantal_tickets = 500;
  15. int totaal_aantal_verkocht = 0;
  16.  
  17. void sell_tickets(pthread_mutex_t *mtx);
  18.  
  19. struct thread_info {
  20.     pthread_t thread_id;
  21.     pthread_mutex_t *mtx;
  22. };
  23.  
  24. static void * thread_start(void *arg) {
  25.     struct thread_info* tinfo = arg;
  26.     sell_tickets(tinfo->mtx);
  27. }
  28.  
  29. int main (int argc, char ** argv) {
  30.     srand(time(NULL));
  31.     struct thread_info *tinfo;
  32.     tinfo = calloc(THREADS, sizeof(struct thread_info));
  33.    
  34.     pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER;
  35.  
  36.     for(int tnum = 0; tnum < THREADS; tnum++) {
  37.         tinfo[tnum].mtx = &mtx;
  38.         pthread_create(&tinfo[tnum].thread_id, NULL, &thread_start, &tinfo[tnum]);
  39.     }
  40.  
  41.     for(int tnum = 0; tnum < THREADS; tnum++) {
  42.         pthread_join(tinfo[tnum].thread_id, NULL);
  43.     }  
  44.  
  45.     printf("totaal tickets verkocht: %d\n", totaal_aantal_verkocht);
  46. }
  47.  
  48. void sell_tickets(pthread_mutex_t *mtx) {
  49.     int aantal_verkocht = 0;
  50.     while(aantal_tickets > 0) {
  51.         // pthread_mutex_lock(mtx);
  52.         if(aantal_tickets > 0) {
  53.             aantal_tickets--;
  54.             aantal_verkocht++;
  55.         }
  56.         // pthread_mutex_unlock(mtx);
  57.         sleep(rand()%3);
  58.     }
  59.     totaal_aantal_verkocht+= aantal_verkocht;
  60.     printf("aantal verkocht: %d\n", aantal_verkocht);
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement