Re: Posix thread exiting and destructors
James Kanze wrote:
On Apr 10, 10:31 am, "Boltar" <boltar2...@yahoo.co.uk> wrote:
I'm writing a threading class using posix threads on unix with each
thread being run by an object instance. One thing I'm not sure about
is , if I do the following:
myclass::~myclass()
{
:
: do stuff
:
pthread_exit(&status);
}
If I exit the thread at the end of the destructor will all the memory
used for the object be free'd?
I wasn't 100% on what you were trying to do... but was this close?
#ifndef Thread_H
#define Thread_H
#define _REENTRANT
class Thread
{
pthread_t thread;
static void * dispatch(void *);
protected:
virtual void run() = 0;
public:
virtual ~Thread(){}
void start();
void join();
};
#endif
..cpp file
-------------------------
#include "Thread.h"
void * Thread::dispatch(void * ptr)
{
if (!ptr)
return 0;
static_cast<Thread *>(ptr)->run();
pthread_exit(ptr);
return 0;
}
void Thread::start()
{
pthread_create(&thread, 0, Thread::dispatch, this);
}
void Thread::join()
{
pthread_join(thread, (void **) 0);
}
This is an ABC, as you can see the derived class must implement a
run() function... When you derived from this, you will call the
start() method wich will create the pthread.. .the creation will
callback the start() function which will execute the derived classes
run(). after run() finishes, pthread_exit() will be called to clean up
the memory.