fork(1) download
  1. #include <iostream>
  2. #include <unordered_map>
  3. #include <vector>
  4. #include <thread>
  5. #include <algorithm>
  6. #include <mutex>
  7. using namespace std;
  8.  
  9. class single
  10. {
  11. public:
  12. // Every thread needs to call this to get its individual instance
  13. static single* getInstance( unsigned int threadId );
  14.  
  15. static void print( unsigned int threadId )
  16. {
  17. std::cout << "threadId:" << threadId << ", Singleton: " << _instances[threadId] << std::endl;
  18. }
  19.  
  20. protected:
  21. // Made protected not private so that singleton can be subclassed
  22. single(); // Clients cant construct objects directly
  23. ~single(); // cannot be destroyed by clients
  24.  
  25. single(const single &) = delete; // non-copyable
  26. single& operator=(const single &) = delete; // can't be copy assigned
  27. single(single &&) = delete; // non-move constructible
  28. single & operator=(single && ) = delete; // non-move assignable
  29.  
  30. private:
  31. static std::unordered_map<unsigned,single*> _instances;
  32. static std::mutex _lock;
  33.  
  34. };
  35.  
  36. std::mutex single::_lock;
  37. std::unordered_map<unsigned,single*> single::_instances;
  38.  
  39. single::single(){}
  40.  
  41. single::~single(){}
  42.  
  43. single* single::getInstance( unsigned int threadId )
  44. {
  45. if( _instances.count( threadId ) == 0 )
  46. {
  47. std::lock_guard<std::mutex> lg(_lock);
  48. if( _instances.count( threadId ) == 0 )
  49. {
  50. _instances[threadId] = new single;
  51. std::cout <<"Created By ThreadId: " << threadId <<std::endl;
  52. }
  53. }
  54.  
  55. return _instances[threadId];
  56. }
  57.  
  58. void Run( unsigned int threadId )
  59. {
  60. single::getInstance(threadId)->print(threadId);
  61. }
  62.  
  63. int main()
  64. {
  65. std::vector<std::thread> workers;
  66. const unsigned threadCount = 16;
  67.  
  68. for( auto i = 0; i != threadCount; ++i )
  69. {
  70. workers.push_back( std::thread( Run, i ) );
  71. }
  72.  
  73. for_each( workers.begin(), workers.end(), std::mem_fn(&thread::join) );
  74.  
  75. return 0;
  76. }
Runtime error #stdin #stdout #stderr 0s 134528KB
stdin
Standard input is empty
stdout
Standard output is empty
stderr
terminate called after throwing an instance of 'std::system_error'
  what():  Resource temporarily unavailable