Advertisement
Guest User

Untitled

a guest
Mar 27th, 2017
53
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.46 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <unistd.h>
  3. #include <pthread.h>
  4. #define NUM_DRIVERS  3
  5. #define NUM_MUTEXES 3
  6. pthread_mutex_t mutex[NUM_MUTEXES];
  7.  
  8. void *driving(void * buyer){
  9.     int num_cars ;
  10.     int buyer_num = *(int*)buyer;
  11.     while(1) {
  12.         for (num_cars = 0; num_cars < NUM_MUTEXES; num_cars ++)
  13.         {
  14.             if(pthread_mutex_trylock(&mutex[num_cars]))
  15.             {
  16.                 printf("Buyer %d takes car %d.\n",buyer_num + 1, num_cars + 1);
  17.                 sleep(0.5);
  18.                 printf("Buyer %d returns car %d.\n",buyer_num + 1, num_cars + 1);
  19.                 pthread_mutex_unlock(&mutex[num_cars]);
  20.             }      
  21.         }
  22.     }
  23.     return NULL;
  24. }
  25.  
  26. int main () {
  27.     pthread_t driver[NUM_DRIVERS];
  28.     int rc;
  29.     int num_drivers, num_threads;
  30.     for(num_threads = 0 ; num_threads < NUM_MUTEXES ; num_threads++)
  31.     {
  32.         if(pthread_mutex_init (&mutex[num_threads], NULL))
  33.         {
  34.             printf("ERROR initing mutex");
  35.             return 0;
  36.         }
  37.     }
  38.    
  39.     for(num_drivers = 0 ; num_drivers < NUM_DRIVERS; num_drivers++)
  40.     {
  41.         rc = pthread_create(&driver[num_drivers], NULL, driving, &num_drivers);
  42.         if(rc)
  43.         {
  44.             printf("ERROR creating thread\n");
  45.             return 0;
  46.         }
  47.     }
  48.  
  49.     for (num_drivers = 0 ; num_drivers < NUM_DRIVERS; num_drivers++)
  50.     {
  51.         if(pthread_join(driver[num_drivers], NULL))
  52.         {
  53.             printf("ERROR joining threads");
  54.             return 0;
  55.         }
  56.     }
  57.    
  58.     for(num_threads = 0 ; num_threads < NUM_MUTEXES ; num_threads++)
  59.     {
  60.         if(pthread_mutex_destroy (&mutex[num_threads]))
  61.         {
  62.             printf("ERROR destroying mutex");
  63.             return 0;
  64.         }
  65.        
  66.     }
  67.    
  68.  
  69.     return 0;
  70. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement