fork download
  1. #include<algorithm>
  2. #include<iostream>
  3. #include<iterator>
  4. #include<mutex>
  5. #include<thread>
  6. #include<vector>
  7.  
  8. std::mutex mutex;
  9. #define PRINT(VALUE) std::cout << __FUNCTION__ << "(" << std::this_thread::get_id() << "): " << VALUE << "\n"
  10.  
  11. namespace Util
  12. {
  13. template<class Class,
  14. class Mutex = std::mutex>
  15. class Concurrent : private Class
  16. {
  17. public: using Class::Class;
  18.  
  19. private: class Safe
  20. {
  21. public: Safe (Concurrent* const this_,
  22. Mutex& rMutex) :
  23. m_This(this_),
  24. m_rMutex(rMutex)
  25. { m_rMutex.lock(); }
  26. public: ~Safe () { m_rMutex.unlock(); }
  27.  
  28. public: Class* operator-> () { return m_This; }
  29. public: const Class* operator-> () const { return m_This; }
  30. public: Class& operator* () { return *m_This; }
  31. public: const Class& operator* () const { return *m_This; }
  32.  
  33. private: Concurrent* const m_This;
  34. private: Mutex& m_rMutex;
  35. };
  36.  
  37. public: Safe ScopeLocked () { return Safe(this, m_Mutex); }
  38. public: const Class* Unsafe () const { return this; }
  39.  
  40. public: Safe operator-> () { return ScopeLocked(); }
  41. public: const Class* operator-> () const { return this; }
  42. public: const Class& operator* () const { return *this; }
  43.  
  44. private: Mutex m_Mutex;
  45. };
  46. }
  47.  
  48. Util::Concurrent<std::vector<int>> vi{8,9};
  49.  
  50. void
  51. Thread ()
  52. {
  53. PRINT("started...");
  54. vi->push_back(2);
  55. PRINT((*vi)[0]);
  56. auto viLocked = vi.ScopeLocked();
  57. std::copy(viLocked->begin(), viLocked->end(), std::ostream_iterator<int>(std::cout, ", "));
  58. std::sort(viLocked->begin(), viLocked->end());
  59. PRINT("copied...");
  60. }
  61.  
  62. int main ()
  63. {
  64. std::thread run(Thread);
  65. PRINT("started...");
  66.  
  67. vi->push_back(1);
  68. {
  69. PRINT("looping...");
  70. auto viLocked = vi.ScopeLocked();
  71. for(auto it = viLocked->begin(); it != viLocked->end(); ++it)
  72. PRINT(*it);
  73. }
  74.  
  75. auto viLocked = vi.ScopeLocked();
  76. auto it = std::begin(*viLocked);
  77. PRINT(*++it);
  78.  
  79. run.join();
  80. }
Time limit exceeded #stdin #stdout 5s 17296KB
stdin
Standard input is empty
stdout
Standard output is empty