Created
August 5, 2014 17:37
-
-
Save daniel-j-h/af57199d523c3397ff07 to your computer and use it in GitHub Desktop.
Thread Guards: The first one takes ownership over the thread, the second one only ensures exception-safe join.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <thread> | |
#include <utility> | |
#include <stdexcept> | |
// takes ownership of the thread | |
class scoped_thread { | |
public: | |
explicit scoped_thread(std::thread t_) : t(std::move(t_)) { | |
if(!t.joinable()) throw std::logic_error{"no thread"}; | |
} | |
~scoped_thread() { t.join(); } | |
scoped_thread(scoped_thread const&) = delete; | |
scoped_thread& operator=(scoped_thread const&) = delete; | |
private: | |
std::thread t; | |
}; | |
// only ensures exception safe join | |
class thread_guard { | |
public: | |
explicit thread_guard(std::thread& t_) : t(t_) {} | |
~thread_guard() { if(t.joinable()) t.join(); } | |
thread_guard(thread_guard const&) = delete; | |
thread_guard& operator=(thread_guard const&) = delete; | |
private: | |
std::thread& t; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment