Advertisement
Guest User

Untitled

a guest
Mar 23rd, 2017
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.37 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <pthread.h>
  3. #include <stdlib.h>
  4. #include <unistd.h>
  5. #include <errno.h>
  6.  
  7. pthread_mutex_t lock[3];
  8.  
  9. void *client(void *arg) {
  10. int num = *((int *) arg) + 1;
  11. int carsused[3] = {0, 0, 0};
  12. while (!(carsused[0] == 1 && carsused[1] == 1 && carsused[2] == 1))
  13. {
  14. for (int i = 0; i < 3; i++)
  15. {
  16. if (carsused[i] == 0)
  17. {
  18. if (pthread_mutex_trylock(&lock[i]) == 0)
  19. {
  20.  
  21. printf("** Buyer %d takes car %d.\n", num, i+1);
  22. sleep(1);
  23. printf("** Buyer %d returns car %d.\n", num, i+1);
  24. pthread_mutex_unlock(&lock[i]);
  25. carsused[i] = 1;
  26. }
  27. }
  28. }
  29. }
  30.  
  31. pthread_exit(NULL);
  32. return 0;
  33. }
  34.  
  35. int main() {
  36.  
  37. pthread_t clients[3];
  38. int *clients_id = malloc(4 * sizeof(int*) );
  39.  
  40. int i;
  41.  
  42. for (i = 0;i<3;i++)
  43. {
  44. clients_id[i] = i;
  45. if (pthread_mutex_init(&lock[i], NULL) != 0)
  46. {
  47. printf("\n mutex init failed\n");
  48. return 1;
  49. }
  50. pthread_create(&clients[i],NULL,client, &clients_id[i]);
  51. }
  52.  
  53. for (i = 0;i<3;i++)
  54. {
  55. pthread_mutex_destroy(&lock[i]);
  56. pthread_join(clients[i],NULL);
  57. }
  58. free(clients_id);
  59.  
  60. return 0;
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement