Re: a really simple C++ abstraction around pthread_t...
On Oct 31, 3:40 pm, "Adem" <for-usenet...@alicewho.com> wrote:
"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' helpe=
r
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 ful=
l
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();
}
<snip>
--
Hmm. is it ok to stay within the ctor for the whole
duration of the lifetime of the object?
It does not stay within the constructor since the constructor
completes after starting a thread.
IMO the ctor should be used only for initializing the object,
That is what is happening. Part of the initialisation is launching a
thread.
but not for executing or calling the "main loop" of the object
The C++ model allows any method calls from the constructor.
12.6.2.9
"Member functions (including virtual member functions, 10.3) can be
called for an object under construction."
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2798.pdf
because the object is fully created only after the ctor has finished,
isn't it?
Yes, it is. In this case the object is fully constructed since the
thread is started in the wrapper after the object has been fully
constructed.
If you are interested in the arguments and counter arguments, you can
check the discussion thread where this construction has emerged:
"What's the connection between objects and threads?"
http://groups.google.com/group/comp.lang.c++/browse_frm/thread/f7cae1851bb5=
f215
Best Regards,
Szabolcs