Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- int a,b;
- int r1,r2;
- mutex m1,m2;
- void th1()
- {
- for(;;)
- {
- m1.lock();
- a=1;
- asm volatile("" ::: "memory");
- r1=b;
- m1.unlock();
- }
- }
- void th2()
- {
- for(;;)
- {
- m2.lock();
- b=1;
- asm volatile("" ::: "memory");
- r2=a;
- m2.unlock();
- }
- }
- int main()
- {
- int cnt{0};
- thread thread1{th1};
- thread thread2{th2};
- thread1.detach();
- thread2.detach();
- for(int i=0;i<10000;i++)
- {
- m1.lock();
- m2.lock();
- a=b=0;
- m1.unlock();
- m2.unlock();
- if(r1==0&&r2==0)
- {
- ++cnt;
- }
- }
- cout<<cnt<<" CPU reorders happened!n";
- }
- #include <mutex>
- #include <condition_variable>
- using namespace std;
- class semaphore{
- private:
- mutex mtx;
- condition_variable cv;
- int cnt;
- public:
- semaphore(int count = 0):cnt(count){}
- void notify()
- {
- unique_lock<mutex> lck(mtx);
- ++cnt;
- cv.notify_one();
- }
- void wait()
- {
- unique_lock<mutex> lck(mtx);
- while(cnt == 0){
- cv.wait(lck);
- }
- --cnt;
- }
- };
- int a,b;
- int r1,r2;
- semaphore s1,s2,s3;
- void th1()
- {
- for(;;)
- {
- s1.wait();
- a=1;
- asm volatile("" ::: "memory");
- r1=b;
- s3.notify();
- }
- }
- void th2()
- {
- for(;;)
- {
- s2.wait();
- b=1;
- asm volatile("" ::: "memory");
- r2=a;
- s3.notify();
- }
- }
- int main()
- {
- int cnt{0};
- thread thread1{th1};
- thread thread2{th2};
- thread1.detach();
- thread2.detach();
- for(int i=0;i<100000;i++)
- {
- a=b=0;
- s1.notify();
- s2.notify();
- s3.wait();
- s3.wait();
- if(r1==0&&r2==0)
- {
- ++cnt;
- }
- }
- cout<<cnt<<" CPU reorders happened!n";
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement