1 | | Based on the scoped_thread class defined in C++ Concurrency in Action define a thread wrapper class that instead of calling terminate if the thread is joinable on destruction, interrupts and join it if joinable. |
| 1 | Based on the scoped_thread class defined in C++ Concurrency in Action define a thread wrapper class that instead of calling terminate if the thread is joinable on destruction, interrupts and join it if joinable. |
| 2 | |
| 3 | While the scoped_thread class defined in C++ Concurrency in Action is a strict scoped class that doesn't allows any change in the wrapped thread, I think that making the interface thread compatible is also a good option. This doesn't means that a strict scoped thread has no use. |
| 4 | |
| 5 | {{{ |
| 6 | namespace boost |
| 7 | { |
| 8 | class scoped_thread |
| 9 | { |
| 10 | thread t; |
| 11 | public: |
| 12 | BOOST_THREAD_NO_COPYABLE( scoped_thread) |
| 13 | explicit scoped_thread(BOOST_THREAD_RV_REF(thread) t_) : |
| 14 | t(move(t_)) |
| 15 | { |
| 16 | } |
| 17 | inline thread::id get_id() const BOOST_NOEXCEPT |
| 18 | { |
| 19 | return t.get_id(); |
| 20 | } |
| 21 | void swap(scoped_thread& x)BOOST_NOEXCEPT |
| 22 | { |
| 23 | t.swap(x.t); |
| 24 | } |
| 25 | void detach() |
| 26 | { |
| 27 | t.detach(); |
| 28 | } |
| 29 | void join() |
| 30 | { |
| 31 | t.join(); |
| 32 | } |
| 33 | template <class Rep, class Period> |
| 34 | bool try_join_for(const chrono::duration<Rep, Period>& rel_time) |
| 35 | { |
| 36 | return t.try_join_for(rel_time); |
| 37 | } |
| 38 | template <class Clock, class Duration> |
| 39 | bool try_join_until(const chrono::time_point<Clock, Duration>& abs_time) |
| 40 | { |
| 41 | return t.try_join_until(abs_time); |
| 42 | } |
| 43 | thread::native_handle_type native_handle() BOOST_NOEXCEPT { |
| 44 | return t.native_handle(); |
| 45 | } |
| 46 | void interrupt() |
| 47 | { |
| 48 | t.interrupt(); |
| 49 | } |
| 50 | |
| 51 | bool interruption_requested() const BOOST_NOEXCEPT |
| 52 | { |
| 53 | return t.interruption_requested(); |
| 54 | } |
| 55 | ~scoped_thread() |
| 56 | { |
| 57 | t.interrupt(); |
| 58 | if (t.joinable()) |
| 59 | { |
| 60 | t.join(); |
| 61 | } |
| 62 | } |
| 63 | }; |
| 64 | inline void swap(scoped_thread& lhs,scoped_thread& rhs) BOOST_NOEXCEPT |
| 65 | { |
| 66 | return lhs.swap(rhs); |
| 67 | } |
| 68 | } |
| 69 | }}} |
| 70 | |
| 71 | |