Advertisement
Guest User

Untitled

a guest
Dec 13th, 2018
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.33 KB | None | 0 0
  1. #include <cstdio>
  2. #include <cstdint>
  3. #include <pthread.h>
  4. #include <stdio.h>
  5. #include <pthread.h>
  6. #include <semaphore.h>
  7. #include <unistd.h>
  8. #include <stdlib.h>
  9. void NewThread(pthread_t *h, void *p(void *arg))
  10. {
  11. int Err;
  12. Err = pthread_create(h, NULL, p, NULL);
  13. if (Err)
  14. fprintf(stderr, "ERROR in NewThread: %d\n", Err);
  15. }
  16. void WaiThread(pthread_t h)
  17. {
  18. int Err;
  19. Err = pthread_join(h, NULL);
  20. if (Err)
  21. fprintf(stderr, "ERROR in WaiThread: %d\n", Err);
  22. }
  23. int S = 2;
  24. sem_t mutex;
  25. void *P1(void *unused)
  26. {
  27. int x;
  28. sem_wait(&mutex);
  29. x = S;
  30. fprintf(stderr, "P1: x = %d\n", x);
  31. x += 2;
  32. S = x;
  33. sem_post(&mutex);
  34. fprintf(stderr, "P1: S = %d\n", S);
  35. return NULL;
  36. }
  37. void *P2(void *unused)
  38. {
  39. int y;
  40. sem_wait(&mutex);
  41. sem_wait(&mutex);
  42. y = S;
  43. fprintf(stderr, "P2: y = %d\n", y);
  44. y += 4;
  45. S = y;
  46. sem_post(&mutex);
  47. fprintf(stderr, "P2: S = %d\n", S);
  48. return NULL;
  49. }
  50. int main()
  51. {
  52. pthread_t p1, p2;
  53. while (true)
  54. {
  55. sem_init(&mutex, 0, 1);
  56. NewThread(&p1, P1);
  57. NewThread(&p2, P2);
  58. //Sleep(1);
  59. fprintf(stderr, "%d\n", S);
  60.  
  61. pthread_cancel(p1);
  62. pthread_cancel(p2);
  63. fprintf(stderr, "\n\n");
  64. S = 2;
  65. }
  66. return 0;
  67. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement