如何从另一个线程获取指针?

m_p*_*tor 3 c++ multithreading

我们有以下类定义:

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;
}
Run Code Online (Sandbox Code Playgroud)

在主程序中,我们有以下内容:

void main(void) {
  CThread thread;
  thread.CreateThread();

  MyClass* myPointer = thread.getMyPointer(); 
  myPointer->someMethod(); // CRASH, BOOM, BANG!!!!
}
Run Code Online (Sandbox Code Playgroud)

在使用myPointer时(在主线程中)它崩溃了.我不知道如何获得指向内存的指针,在另一个线程中分配.这有可能吗?

Rob*_*ker 11

所有线程都可以访问应用程序的内存空间.默认情况下,无论上下文如何,任何线程都可以看到任何变量(唯一的例外是声明__delcspec(thread)的变量)

由于竞争条件,你正在崩溃.刚刚创建的线程在调用getMyPointer时尚未开始运行.您需要在新创建的线程和原始线程之间添加某种同步.换句话说,原始线程必须等到新线程发信号通知它已创建对象.