Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <thread>
- #include <mutex>
- #include <condition_variable>
- std::mutex m;
- std::mutex cos;
- std::mutex sin;
- void bar(){
- std::unique_lock <std::mutex> lock(m);
- std::unique_lock <std::mutex> lock_sin(sin);
- std::unique_lock <std::mutex> lock_cos(cos, std::defer_lock);
- bool cs = true;
- bool tr = false;
- printf("gnop");
- lock.unlock();
- for(size_t i = 1; i < 500000; ++i) {
- while (!lock.try_lock()) {}
- //printf("i m locked\n");
- tr = lock_cos.try_lock();
- if(tr == cs){
- if(tr){
- //printf("cos locked\n");
- lock_cos.unlock();
- //printf("cos unlocked\n");
- }
- --i;
- //printf("yield\n");
- lock.unlock();
- std::this_thread::yield();
- continue;
- } else if(tr){
- //printf("cos locked\n");
- lock_cos.unlock();
- //printf("cos unlocked\n");
- lock_sin.lock();
- //printf("sin locked\n");
- } else{
- lock_sin.unlock();
- //printf("sin unlocked\n");
- }
- cs = tr;
- printf("gnop\n");
- lock.unlock();
- }
- }
- void foo(){
- std::unique_lock <std::mutex> lock_cos(cos, std::defer_lock);
- std::unique_lock <std::mutex> lock_sin(sin, std::defer_lock);
- std::unique_lock <std::mutex> lock(m,std::defer_lock);
- bool sn = true;
- bool tr = false;
- for(size_t i = 0; i < 500000; ++i) {
- while (!lock.try_lock()) {}
- //printf("o m locked\n");
- tr = lock_sin.try_lock();
- if(tr == sn){
- if(tr){
- //printf("sin locked\n");
- lock_sin.unlock();
- //printf("sin unlocked\n");
- }
- --i;
- //printf("yield\n");
- lock.unlock();
- std::this_thread::yield();
- continue;
- } else if(tr){
- //printf("sin locked\n");
- lock_sin.unlock();
- //printf("sin unlocked\n");
- lock_cos.unlock();
- //printf("cos unlocked\n");
- } else{
- lock_cos.lock();
- //printf("cos locked\n");
- }
- sn = tr;
- printf("gnip\n");
- lock.unlock();
- }
- }
- int main(int argc, char const *argv[]) {
- std::thread T1 (bar);
- T1.detach();
- std::thread T2 (foo);
- T2.join();
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement