vladkomarr

scoped thread

Dec 30th, 2015
155
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.12 KB | None | 0 0
  1. #include <iostream>
  2. #include <thread>
  3. #include <memory>
  4.  
  5. class ScopedThread
  6. {
  7.     std::thread m_thread;
  8.  
  9. public:
  10.     explicit ScopedThread(std::thread t)
  11.         : m_thread(std::move(t))
  12.     {
  13.         if (!m_thread.joinable())
  14.         {
  15.             throw std::logic_error("No thread");
  16.         }
  17.     }
  18.  
  19.     ~ScopedThread()
  20.     {
  21.         m_thread.join();
  22.     }
  23.  
  24.     ScopedThread(const ScopedThread&) = delete;
  25.     ScopedThread& operator=(const ScopedThread&) = delete;
  26. };
  27.  
  28. struct func
  29. {
  30.     int& i;
  31.  
  32.     func(int& i_) : i(i_) { }
  33.  
  34.     void operator()()
  35.     {
  36.         for (auto j = 0; j < 10000000; ++j)
  37.         {
  38.             std::cout << i + j << std::endl;
  39.         }
  40.     }
  41. };
  42.  
  43. int main()
  44. {
  45.     auto state = 0;
  46.  
  47.     ScopedThread t(std::thread(func(state)));
  48.  
  49.     /*  ^ not working
  50.      *  It is treated like function declaration
  51.      *  rather than object initialization.
  52.      *  Thus, one should use double parentheses:
  53.      *      ScopedThread t((std::thread(func(state))));
  54.      *  or uniform initialization:
  55.      *      ScopedThread t { std::thread(func(state)) };
  56.     */
  57.  
  58.     return 0;
  59. }
Advertisement
Add Comment
Please, Sign In to add comment