Advertisement
Guest User

Untitled

a guest
Apr 23rd, 2014
46
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.82 KB | None | 0 0
  1. int a,b;
  2. int r1,r2;
  3. mutex m1,m2;
  4.  
  5. void th1()
  6. {
  7. for(;;)
  8. {
  9. m1.lock();
  10. a=1;
  11. asm volatile("" ::: "memory");
  12. r1=b;
  13. m1.unlock();
  14. }
  15. }
  16.  
  17. void th2()
  18. {
  19. for(;;)
  20. {
  21. m2.lock();
  22. b=1;
  23. asm volatile("" ::: "memory");
  24. r2=a;
  25. m2.unlock();
  26. }
  27. }
  28.  
  29. int main()
  30. {
  31. int cnt{0};
  32. thread thread1{th1};
  33. thread thread2{th2};
  34. thread1.detach();
  35. thread2.detach();
  36. for(int i=0;i<10000;i++)
  37. {
  38. m1.lock();
  39. m2.lock();
  40. a=b=0;
  41. m1.unlock();
  42. m2.unlock();
  43. if(r1==0&&r2==0)
  44. {
  45. ++cnt;
  46. }
  47. }
  48. cout<<cnt<<" CPU reorders happened!n";
  49. }
  50.  
  51. #include <mutex>
  52. #include <condition_variable>
  53. using namespace std;
  54.  
  55. class semaphore{
  56. private:
  57. mutex mtx;
  58. condition_variable cv;
  59. int cnt;
  60.  
  61. public:
  62. semaphore(int count = 0):cnt(count){}
  63. void notify()
  64. {
  65. unique_lock<mutex> lck(mtx);
  66. ++cnt;
  67. cv.notify_one();
  68. }
  69. void wait()
  70. {
  71. unique_lock<mutex> lck(mtx);
  72.  
  73. while(cnt == 0){
  74. cv.wait(lck);
  75. }
  76. --cnt;
  77. }
  78. };
  79.  
  80. int a,b;
  81. int r1,r2;
  82. semaphore s1,s2,s3;
  83.  
  84. void th1()
  85. {
  86. for(;;)
  87. {
  88. s1.wait();
  89. a=1;
  90. asm volatile("" ::: "memory");
  91. r1=b;
  92. s3.notify();
  93. }
  94. }
  95.  
  96. void th2()
  97. {
  98. for(;;)
  99. {
  100. s2.wait();
  101. b=1;
  102. asm volatile("" ::: "memory");
  103. r2=a;
  104. s3.notify();
  105. }
  106. }
  107.  
  108. int main()
  109. {
  110. int cnt{0};
  111. thread thread1{th1};
  112. thread thread2{th2};
  113. thread1.detach();
  114. thread2.detach();
  115. for(int i=0;i<100000;i++)
  116. {
  117. a=b=0;
  118. s1.notify();
  119. s2.notify();
  120. s3.wait();
  121. s3.wait();
  122.  
  123. if(r1==0&&r2==0)
  124. {
  125. ++cnt;
  126. }
  127. }
  128. cout<<cnt<<" CPU reorders happened!n";
  129. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement