Guest User

Untitled

a guest
Jun 18th, 2018
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.26 KB | None | 0 0
  1. class PFBackgroundService : public IBackgroundService
  2. {
  3. private:
  4.  
  5. //thread-safe wrapper class for a promise/future pair
  6. template <typename T>
  7. struct PromiseAndFuture
  8. {
  9. std::unique_ptr<std::promise<T>> m_promise;
  10. std::unique_ptr<std::future<T>> m_future;
  11. std::mutex m_mutex;
  12.  
  13. //constructor
  14. PromiseAndFuture()
  15. {
  16. reset();
  17. }
  18.  
  19. //reset the managed promise and future objects to new ones
  20. void reset()
  21. {
  22. m_promise.reset(nullptr);
  23. m_future.reset(nullptr);
  24. m_promise = std::make_unique<std::promise<T>>();
  25. m_future = std::make_unique<std::future<T>>(m_promise->get_future());
  26. }
  27.  
  28. //non-blocking function that returns whether or not the
  29. //managed future object is ready, i.e., has a valid value
  30. bool ready()
  31. {
  32. std::future_status status = m_future->wait_for(std::chrono::milliseconds(0));
  33. return (status == std::future_status::ready);
  34. }
  35.  
  36. //blocking function that retrieves and returns value in
  37. //managed future object
  38. T get()
  39. {
  40. std::lock_guard<std::mutex> lockGuard(m_mutex);
  41. T ret = m_future->get();
  42. reset();
  43. return ret;
  44. }
  45.  
  46. //set the value on the managed promise object to val,
  47. //thereby making the future "ready" and contain val
  48. bool set(T val)
  49. {
  50. std::lock_guard<std::mutex> lockGuard(m_mutex);
  51. //don't
  52. if (ready())
  53. {
  54. return false;
  55. }
  56. m_promise->set_value(val);
  57. return true;
  58. }
  59. };
  60.  
  61. //managed background thread
  62. std::unique_ptr<std::thread> m_thread;
  63.  
  64. //instance of promise/future pair that is used for messaging
  65. PromiseAndFuture<std::string> m_PF;
  66.  
  67. //stop message
  68. const static std::string STOP;
  69.  
  70. public:
  71. //constructor (takes in fptr to a "reactor" function that "reacts"
  72. //to a string message)
  73. PFBackgroundService(const std::function<void(std::string)>& reactor);
  74.  
  75. //interface method
  76. void processMessage(std::string msg);
  77.  
  78. //destructor (stops and waits for managed thread to exit)
  79. ~PFBackgroundService();
  80. };
Add Comment
Please, Sign In to add comment