Advertisement
Guest User

Untitled

a guest
Apr 26th, 2019
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.70 KB | None | 0 0
  1. #include <iostream>
  2. #include <pthread.h>
  3. #include <stdio.h>
  4. #include <unistd.h>
  5. #include <errno.h>
  6. //perror, strerror, вывести сообщение об ошибке
  7. using namespace std;
  8.  
  9. pthread_mutex_t mtx;
  10.  
  11. void *thread1(void *flag)
  12. {
  13. cout << "start thread 1\n";
  14. timespec timer;
  15. while (*(int*)flag != 0)
  16. {
  17. clock_gettime(CLOCK_REALTIME, &timer);
  18. timer.tv_sec += 2;
  19. if (pthread_mutex_timedlock(&mtx, &timer) == 0)
  20. {
  21. for (int i = 0; i < 2; i++)
  22. {
  23. cout << "1";
  24. fflush(stdout);
  25. sleep(1);
  26. }
  27. pthread_mutex_unlock(&mtx);
  28. sleep(2);
  29. }
  30. else
  31. {
  32. cout << "Mutex is unavailable" << "\n";
  33. fflush(stdout);
  34. if (*(int*)flag == 0) break;
  35. sleep(1);
  36. }
  37.  
  38. }
  39.  
  40. cout << "\nend thread 1\n";
  41. return 0;
  42. }
  43.  
  44. void *thread2(void *flag)
  45. {
  46. cout << "\nstart thread 2\n";
  47. timespec timer;
  48. while (*(int*)flag != 0)
  49. {
  50. clock_gettime(CLOCK_REALTIME, &timer);
  51. timer.tv_sec += 3;
  52. if (pthread_mutex_timedlock(&mtx, &timer) == 0)
  53. {
  54. for (int i = 0; i < 2; i++)
  55. {
  56. cout << "2";
  57. fflush(stdout);
  58. sleep(1);
  59. }
  60. pthread_mutex_unlock(&mtx);
  61. sleep(2);
  62. }
  63. else
  64. {
  65. cout << "Mutex is unavailable" << "\n";
  66. fflush(stdout);
  67. if (*(int*)flag == 0) break;
  68. sleep(1);
  69. }
  70. }
  71.  
  72. cout << "\nend thread 2\n";
  73. return 0;
  74. }
  75.  
  76. int main()
  77. {
  78. int fl1, fl2;
  79. void *retval[2];
  80. pthread_t thr1, thr2;
  81. pthread_mutex_init(&mtx, NULL);
  82. fl1 = fl2 = 1;
  83. pthread_create(&thr1, NULL, &thread1, &fl1);
  84. pthread_create(&thr2, NULL, &thread2, &fl2);
  85. getchar();
  86. fl1 = fl2 = 0;
  87. cout << "\n";
  88. pthread_join(thr1, &retval[0]);
  89. pthread_join(thr2, &retval[1]);
  90. pthread_mutex_destroy(&mtx);
  91. return 0;
  92. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement