1


我正在尝试将结构传递给我的线程 CreateThread(),这是我的结构:

struct Secure
{
  int UID;
  LPVOID MainClass;
};

这是我打电话的方式CreateThread()

Secure m_Secure = {Room->g_User[PlayerNumber].UID,this};

CreateThread(NULL,NULL,(LPTHREAD_START_ROUTINE)SecureThread,&m_Secure,NULL,NULL);

其中第一个是整数,第二个是指向当前类的指针。
而且,这是我的线程,我认为这就是问题所在

HRESULT WINAPI SecureThread(LPVOID Param)
{
    int UID = -1, UserNumber, i;

    Secure* m_Secure = (Secure*)Param;

    UID = m_Secure->UID;

    CGGCBotDlg *h_MainClass = (CGGCBotDlg*)m_Secure->MainClass;

    if (UID == -1) return 0;

    Sleep(25000);

    for (i = 0; i < TOTAL_CLIENTS; i++)
    {
        if (h_MainClass->Room->g_User[i].UID == UID)
        {
            UserNumber = i;
            break;
        }
    }

    if( h_MainClass->Room->g_User[UserNumber].IsFree == false && h_MainClass->Room->g_User[UserNumber].Secured == false)
        h_MainClass->Room->Kick(h_MainClass->Room->g_User[UserNumber].UID,"Didn't Authorized");

    return 0;
}

每当创建此线程时,程序就会崩溃,这是一个例外:

First-chance exception at 0x00EC3548 in GGCRoomServer.exe: 0xC0000005: Access violation reading location 0x5D00009C.
Unhandled exception at 0x00EC3548 in GGCRoomServer.exe: 0xC0000005: Access violation reading location 0x5D00009C.
4

2 回答 2

2

创建一个堆变量来保存您的数据并将其传递给线程。

Secure * m_Secure = new Secure();
m_Secure->UID = g_User[PlayerNumber].UID;
m_Secure->MainClass = this;
CreateThread(NULL,NULL,(LPTHREAD_START_ROUTINE)SecureThread,m_Secure,NULL,NULL);

获取线程中的数据,完成后删除

RESULT WINAPI SecureThread(LPVOID Param)
{
    int UID = -1, UserNumber, i;

    Secure* m_Secure = (Secure*)Param;
....
    delete m_Secure;
    return 0;
}
于 2013-09-26T10:07:58.023 回答
2

看起来您正在将局部变量的地址传递给此处的线程

Secure m_Secure = {Room->g_User[PlayerNumber].UID,this};    
CreateThread(NULL,NULL,(LPTHREAD_START_ROUTINE)SecureThread,&m_Secure,NULL,NULL);

作为局部变量,m_Secure将超出范围并在函数执行完成后被销毁。此外,m_Secure 很可能是在堆栈上创建的。将一个线程的堆栈变量地址传递给另一个线程通常是一个坏主意
您需要在堆上创建变量
类似于

CreateThread(NULL,NULL,(LPTHREAD_START_ROUTINE)SecureThread,new Secure(...),NULL,NULL);
                                                            ^^^^^^^^^^^^^^

并且不要忘记之后删除指针

于 2013-09-26T10:10:03.483 回答