Click to See Complete Forum and Search --> : executing a member function in a separate thread


singersinger
10-16-2006, 05:39 AM
hello everybody !!

my new problem is that i have a class that contain a some functions and some variables

i want to execute one of these functions in a separate thread using AfxBeginThread(...);
and FYI this function uses some member variables of the class to do it's work

any idea ???
thnx 4 ur time and concern

a.hemdan

Viorel
10-16-2006, 05:56 AM
When you create the thread with AfxBeginThread (the first form), you can specify a parameter which is passed to the thread procedure. Pass a pointer to your object, then cast it and call the member function:

class MyObject
{
void myFunction();
. . .
};

static UINT __cdecl MyThreadProc( LPVOID pParam )
{
((MyObject*)pParam)->myFunction();
return 0;
}

. . .

MyObject * myObject = ...;

AfxBeginThread(MyThreadProc, myObject);

The above sample calls the myFunction member function only. If you need to call various member functions, you have to adjust the solution using pointers-to-member.

Note that you have to use a synchronization technique (e.g. "critical sections") if you access data from different threads.

I hope this helps.

drkybelk
10-16-2006, 05:58 AM
Hi,
Your thread function itself has to be a static member. AfxBeginThread only takes static members or normal (non-member) functions. Hence you cannot use any non-static members in your thread-function. But there is a workaround. Add a static pointer to your class pointing to an instance of your class. Make sure you create a valid object before you call AfxBeginThread.

*.h - file

class MyClass
{
static MyClass* pThis;
public:
MyClass()
{
pThis = new MyClass;
....
}
static void threadFunction(void* p)
{
// do your thread functionality here
if(pThis)
{
// access pThis - members...
pThis->nonstaticMember();
}
}

void startMyThread()
{
AfxBeginThread(threadFunction,NULL);
}
};


This code fragment probably points you into the right direction...
Cheers,
D

make

Danny
10-16-2006, 11:35 AM
Further info about this technique is available here: http://www.devx.com/DevX/LegacyLink/9483