Let’s have the following class definition:
CThread::CThread () { this->hThread = NULL; this->hThreadId = 0; this->hMainThread = ::GetCurrentThread (); this->hMainThreadId = ::GetCurrentThreadId (); this->Timeout = 2000; //milliseconds } CThread::~CThread () { //waiting for the thread to terminate if (this->hThread) { if (::WaitForSingleObject (this->hThread, this->Timeout) == WAIT_TIMEOUT) ::TerminateThread (this->hThread, 1); ::CloseHandle (this->hThread); } } //********************************************************* //working method //********************************************************* unsigned long CThread::Process (void* parameter) { //a mechanism for terminating thread should be implemented //not allowing the method to be run from the main thread if (::GetCurrentThreadId () == this->hMainThreadId) return 0; else { m_pMyPointer = new MyClass(...); // my class successfully works here in another thread return 0; } } //********************************************************* //creates the thread //********************************************************* bool CThread::CreateThread () { if (!this->IsCreated ()) { param* this_param = new param; this_param->pThread = this; this->hThread = ::CreateThread (NULL, 0, (unsigned long (__stdcall *)(void *))this->runProcess, (void *)(this_param), 0, &this->hThreadId); return this->hThread ? true : false; } return false; } //********************************************************* //creates the thread //********************************************************* int CThread::runProcess (void* Param) { CThread* thread; thread = (CThread*)((param*)Param)->pThread; delete ((param*)Param); return thread->Process (0); } MyClass* CThread::getMyPointer() { return m_pMyPointer; }
In the main program, we have the following:
void main(void) { CThread thread; thread.CreateThread(); MyClass* myPointer = thread.getMyPointer(); myPointer->someMethod(); // CRASH, BOOM, BANG!!!! }
At the moment the myPointer is used ( in the main thread ) it crashes. I don’t know how to get the pointer, which points to memory, allocated in another thread. Is this actually possible?
The memory space for your application is accessible to all threads. By default any variable is visible to any thread regardless of context (the only exception would be variables declared __delcspec(thread) )
You are getting a crash due to a race condition. The thread you just created hasn’t started running yet at the point where you call getMyPointer. You need to add some kind of synchronization between the newly created thread and the originating thread. In other words, the originating thread has to wait until the new thread signals it that it has created the object.