jack06215

[tools] barter

Jul 8th, 2020 (edited)
152
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.84 KB | None | 0 0
  1. #ifndef __BARTER_HPP__
  2. #define __BARTER_HPP__
  3.  
  4. #include <memory>  // std::unique_ptr
  5. #include <atomic>  // std::atomic
  6.  
  7.  
  8. /*
  9.   Description:
  10.     A simple header-only class template to allow safe data exchange between threads.
  11.  */
  12. template <typename Typ_, typename Del_ = std::default_delete<Typ_> >
  13. class barter {
  14.  
  15.     // The shared object: the only contact point between two threads
  16.     std::atomic<Typ_ *> _pinned_object;
  17.  
  18. public:
  19.     using Ptr = std::unique_ptr < Typ_, Del_ > ;
  20.  
  21.     barter()
  22.     {
  23.         _pinned_object = new Typ_{};
  24.     }
  25.  
  26.     ~barter()
  27.     {
  28.         // call the destructor for the pinned_object
  29.         Ptr().reset(_pinned_object);
  30.     }
  31.  
  32.     void exchange(Ptr & p_)
  33.     {
  34.         Typ_ * oldptr = _pinned_object.exchange(p_.release());
  35.         p_.reset(oldptr);
  36.     }
  37. };
  38.  
  39. #endif  // !__BARTER_HPP__
Add Comment
Please, Sign In to add comment