Ok, I have googled this and everything which made me do this the way I try in the first place. The actual thread is defined as friend because AfxBeginThread only takes static functions, and a pointer to the class instance is passed as argument.
But I just can't see why this is wrong.
Really glad for an explanation / correct way to do it.
Now, I wrote this as a maximally stripped down version and like this it obviously doesn't make a lot of sense.
But what I really want to do is have a thread which, as argument, receives a pointer to a class instance, and can thus manipulate class variables. Sounds easy, no?
Well, the way I tried to do it, it compiles but doesn't run, following error in the line printed in
bold
Unhandled exception at 0x0041186d in simpleThread.exe: 0xC0000005: Access violation reading location 0xccccccd0.
class testClass{
public:
testClass();
CEvent* pEvent;
CWinThread* pThread;
friend UINT ThreadProc(LPVOID lpParameter);
void startThread();
void sendEvent();
};
int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{
testClass myInstance;
myInstance.startThread();
Sleep(2000);
myInstance.sendEvent();
return 0;
}
UINT ThreadProc( LPVOID lpParameter )
{
testClass* instance = (testClass*)(lpParameter);
WaitForSingleObject( instance->pEvent->m_hObject, INFINITE );
return 0L;
}
testClass::testClass(){
CEvent* pEvent = new CEvent( FALSE, FALSE );
}
void testClass::startThread()
{
pThread = ::AfxBeginThread( ThreadProc, this, 0, 0,
CREATE_SUSPENDED, NULL);
pThread->m_bAutoDelete = FALSE;
pThread->ResumeThread();
}
void testClass::sendEvent()
{
pEvent->SetEvent();
}
P.S.: My code is based on
http://msdn.microsoft.com/en-us/library/efk30beh%28v=vs.80%29.aspx[
^] which is very similar, except they don't try to wrap it all up in a class.
Many thanks for solutions / suggestions.