"Chris M. Thomasson" wrote
"Chris M. Thomasson" wrote
I use the following technique in all of my C++ projects; here is the
example code with error checking omitted for brevity:
[...]
Any suggestions on how I can improve this construct?
One addition I forgot to add would be creating an explict `guard' helper
object within the `active' helper object so that one can create objects and
intervene between its ctor and when it actually gets ran... Here is full
example code showing this moment:
_________________________________________________________________
/* Simple Thread Object
______________________________________________________________*/
#include <pthread.h>
extern "C" void* thread_entry(void*);
class thread_base {
pthread_t m_tid;
friend void* thread_entry(void*);
virtual void on_active() = 0;
public:
virtual ~thread_base() = 0;
void active_run() {
pthread_create(&m_tid, NULL, thread_entry, this);
}
void active_join() {
pthread_join(m_tid, NULL);
}
};
thread_base::~thread_base() {}
void* thread_entry(void* state) {
reinterpret_cast<thread_base*>(state)->on_active();
return 0;
}
template<typename T>
struct active : public T {
struct guard {
T& m_object;
guard(T& object) : m_object(object) {
m_object.active_run();
}
~guard() {
m_object.active_join();
}
};
active() : T() {
this->active_run();
}
Hmm. is it ok to stay within the ctor for the whole