Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <thread>
- #include <memory>
- class ScopedThread
- {
- std::thread m_thread;
- public:
- explicit ScopedThread(std::thread t)
- : m_thread(std::move(t))
- {
- if (!m_thread.joinable())
- {
- throw std::logic_error("No thread");
- }
- }
- ~ScopedThread()
- {
- m_thread.join();
- }
- ScopedThread(const ScopedThread&) = delete;
- ScopedThread& operator=(const ScopedThread&) = delete;
- };
- struct func
- {
- int& i;
- func(int& i_) : i(i_) { }
- void operator()()
- {
- for (auto j = 0; j < 10000000; ++j)
- {
- std::cout << i + j << std::endl;
- }
- }
- };
- int main()
- {
- auto state = 0;
- ScopedThread t(std::thread(func(state)));
- /* ^ not working
- * It is treated like function declaration
- * rather than object initialization.
- * Thus, one should use double parentheses:
- * ScopedThread t((std::thread(func(state))));
- * or uniform initialization:
- * ScopedThread t { std::thread(func(state)) };
- */
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment