Run C++ class functions in thread

I have changed the question with a simpler example to understand the problem:
Suppose we have class rectangle
class CRectangle
{
int x, y;
public:
void set_values (int a,int b)
{
x = a;
y = b;
}

void get_values (int &a,int &b)
{
a = x;
b = y;
}

int area () {return (x*y);}
};


int main ()
{
int &x, &y;
CRectangle rect;

rect.set_values (3,4);

rect.get_values (x,y);
cout << "x = " << x << “y = ” << y;

cout << "area: " << rect.area();

return 0;
}


Here you see that we creating an object in main fn and depending on our need calling the various fns of the class.

Now I want to make this class threadable in the sense I want to the class fns to be executed in a thread.
So I wrote the following class:
class Thread
{
Thread *threadptr;
HANDLE ThreadHandle;

public:
Thread()
{
Thread = 0;
}

void start()
{
DWORD threadID;

threadptr = this;
ThreadHandle = CreateThread(0, 0, entrypoint, threadptr, 0, &threadID);
}

void stop()
{

CloseHandle (ThreadHandle, 0);
}

static unsigned long entrypoint(void* ptr)
{
((Thread*)ptr)->execute();
return 0;
}
virtual void execute() = 0;
};

Usage of thread class:
class CRectangle: public Thread
{
private:
int x, y;
void set_values (int a,int b)
{
x = a;
y = b;
}

void get_values (int &a,int &b)
{
a = x;
b = y;
}

int area () {return (x*y);}

public:
CRectangle () { }
~ CRectangle () { }

//the execute function, you need to override this one
void execute()
{
//Add your threaded code here
}

};

int main()
{
CRectangle obj;

obj.start();
obj.stop();

return 0;
}


Now I want to know how to call ALL the various fns of class rectangle from within execute() in the same way as I called in main earlier.
Last edited on
Call fn1(), fn2(), etc from execute(), which is the equivalent of main() for your thread.

I assume you that your main will start and then immediately "stop" the thread by exiting the program?

Also, closing a thread handle does not stop a thread. It just leaves in running.
Thanks andy for the reply.
This program I worte was just for asking the question and I will have some while loop for the execute() to run infinetley.

I am not able to imagine how to call other fns from execute depending upon on our need.
Can you give me some example?
If you have no problem coding a main() function, then you should have no problem with a "thread main". Any function called from execute(), or from a function called from execute, etc. will be called on the thread.
Topic archived. No new replies allowed.