Skip to content

Instantly share code, notes, and snippets.

@daniel-j-h
Created August 5, 2014 17:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save daniel-j-h/af57199d523c3397ff07 to your computer and use it in GitHub Desktop.
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.
#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