Click to See Complete Forum and Search --> : MFC Worker Threads ??


sfought
April 22nd, 1999, 03:21 PM
I have an ActiveX control that uses a worker thread. I need the worker thread to be able to fire events for the control, so I am trying to declare the worker thread's function as a member of the class, but I am getting the following compiler error:

'AfxBeginThread' : none of the 2 overloads can convert parameter 1 from type 'unsigned int (void *)'

The code looks like this

// This is in the class declaration

private:
UINT WorkerThread(LPVOID pInfo);

// This is in one of the classes member functions

AfxBeginThread(WorkerThread, NULL, 0, 0, 0, NULL);

// And this is the way the actual function is defined

UINT MyClass::WorkerThread(LPVOID pInfo)

Is there a way that I can type-cast WorkerThread in the call to AfxBeginThread? Or is there a way I can have a non-member function fire the classes event? Has anyone run into this before?

Thanks,
sfought

MoMoPi
April 22nd, 1999, 03:38 PM
I hope the follwoing sample codes will help you.

UINT MyThreadProc( LPVOID pParam )
{
CMyObject* pObject = (CMyObject*)pParam;
if (pObject == NULL ||
!pObject->IsKindOf(RUNTIME_CLASS(CMyObject)))
return 1;

// do something with 'pObject'
return 0; // thread completed successfully
}
//inside a different function in the program
.
.
.
pNewObject = new CMyObject;
AfxBeginThread(MyThreadProc, pNewObject);

sfought
April 22nd, 1999, 03:50 PM
Is there a way that I can make the worker thread a member of the controls class?

Thanks,
sfought

April 23rd, 1999, 02:04 AM
You can make the threadproc a member of your class if you make it static.

Mats Bejedahl

April 23rd, 1999, 08:33 AM
Use a User Interface thread (CWinThread) instead, then override the virtual
function 'Run' to turn it into a Worker Thread.

This way the thread is a proper class without any static members.

eg.
class CMyThread : public CWinThread
....

In the Run function you could have a forever loop which waits on events,
when the Event is set some work is performed.
When the Run function exits the Thread terminates automatically.
The thread is started normally with

m_pThread = (CMyThread*) AfxBeginThread(RUNTIME_CLASS(CMyThread));

Jeff Nuttall

MoMoPi
April 23rd, 1999, 09:12 AM
for example:

If you have a worker thread in CView.

//in the header

public:
void StartThread();

// Generated message map functions
protected:
//{{AFX_MSG(Yoiurclassname)
afx_msg void OnNewThread();
DECLARE_MESSAGE_MAP()
};

// in the cpp file

BEGIN_MESSAGE_MAP(yourclassname, CView)
//{{AFX_MSG_MAP(yourclassname)
ON_COMMAND(ID_NEW_*****, OnNewThread)
END_MESSAGE_MAP()

void Cyourclassname::StartThread()
{
use your worker class here.
}

void Cyourclassname::OnNewThread()
{
StartThread();

}


PS: I hope this will help you. if you really need a real code, let me know.