Advertisement
Guest User

Untitled

a guest
Jul 19th, 2019
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.84 KB | None | 0 0
  1. //
  2. //  exchanger.cpp
  3. //  malnati
  4. //
  5. //  Created by Elia Migliore on 19/07/2019.
  6. //  Copyright © 2019 Elia Migliore. All rights reserved.
  7. //
  8.  
  9. #include "exchanger.hpp"
  10. #include <iostream>
  11. #include <mutex>
  12. #include <thread>
  13.  
  14. template <typename T>
  15.  
  16. class Exchanger {
  17.     T exchanged;
  18.     bool is_exchanged;
  19.     std::mutex m_protect_data;
  20.     std::mutex m_protect_sleep;
  21.     std::condition_variable cv;
  22.    
  23.     Exchanger(T& exchanged) {
  24.         std::unique_lock<std::mutex> l(m_protect_data);
  25.        
  26.         if (is_exchanged){
  27.             // cv.signal()
  28.             std::swap(exchanged, this->exchanged);
  29.             cv.notify_one();
  30.            
  31.         } else {
  32.            
  33.             // exchange the item and set to true the variable
  34.             // that represent the exchanged flag
  35.             this->exchanged = exchanged;
  36.             is_exchanged = true;
  37.            
  38.             // release the lock for protecting the variable
  39.             l.release();
  40.            
  41.             // wait for the other thread to wake me up when
  42.             // another element has arrived and the exchanged
  43.             // item is exchanged
  44.            
  45.             // unique lock per il paradisma RAII
  46.             std::unique_lock<std::mutex> l_s(m_protect_sleep);
  47.             cv.wait(l_s);
  48.            
  49.            
  50.             // getting again te lock to protect the flag and data
  51.             l.lock();
  52.             exchanged = this->exchanged;
  53.             is_exchanged = false; // restore the class for next use
  54.            
  55.             // now RAII paradigm release the second lock for me
  56.         }
  57.         // output to indicate the success
  58.         std::cout << "element to exchange is: " << typeid(exchanged).name() << std::endl;
  59.        
  60.        
  61.         // now RAII paradigm release the first lock for me
  62.     }
  63.    
  64.    
  65. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement