2012-11-22 38 views
1

頭文件引用的結構類:故障使用此關鍵字

// Free function to use in thread 
unsigned int __stdcall WorkerFunction(void *); 

class MyClass { 
    public: 
     int temp; 
     void StartThread(); 
} 

typedef struct { 
    MyClass * cls; 
} DATA; 

CPP類:

void MyClass::StartThread() { 
    temp = 1234; 
    DATA data = {this}; 

    HANDLE hThread = (HANDLE) _beginthreadex(0, 0, &WorkerFunction, &data, 0, 0); 

    // Commented out for now while I address the current problem 
    //CloseHandle(hThread); 
} 

unsigned int __stdcall WorkerFunction(void * param0) { 
    MessageBox(NULL, "WorkerFunction()", "Alert", MB_OK); 
    DATA * data = (DATA *) param0; 
    MyClass* cls0 = data->cls; 

    // Crashes when reference to cls0 is attempted. 
    char buf[5]; 
    snprintf(buf, 5, "%i", cls0 ->temp); 
    MessageBox(NULL, buf, "Alert", MB_OK); 
} 

我有一個簡單的問題,在這裏,我不能把我的手指上。

  • 我有一個線程,它傳遞一個包含類的結構的參數。
  • 我使用this實例化結構,然後在線程啓動時傳遞它
  • 我嘗試在worker函數中取消引用(?)它。
  • 在這一點上,一切都編譯好。
  • 當我添加行來訪問類中的某些東西時,應用程序崩潰。

我的錯誤在哪裏?

回答

1

您正在傳遞一個本地堆棧變量,該變量在StartThread()返回時超出範圍。因此,您正在引用不再屬於您的堆棧空間。

void MyClass::StartThread() { 
    temp = 1234; 
    DATA data = {this}; // << LOCAL VARIABLE OUT OF SCOPE ON FUNCTION EXIT 

    HANDLE hThread = (HANDLE) _beginthreadex(0, 0, &WorkerFunction, &data, 0, 0); 

    // Commented out for now while I address the current problem 
    //CloseHandle(hThread); 
} 

要麼動態地分配數據,或者更好的是,使數據的MyClass一個構件,並通過this作爲線程數據。在你的情況你只有通過*這個反正通過結構,所以只是把它作爲帕拉姆

void MyClass::StartThread() { 
    temp = 1234; 

    HANDLE hThread = (HANDLE) _beginthreadex(0, 0, &WorkerFunction, this, 0, 0); 

    // Commented out for now while I address the current problem 
    //CloseHandle(hThread); 
} 

而且在你的線程PROC:

unsigned int __stdcall WorkerFunction(void * param0) { 
    MessageBox(NULL, "WorkerFunction()", "Alert", MB_OK); 
    MyClass* cls0 = static_cast<MyClass*>(param0); 

    etc... 
} 

無論你傳遞給你的線程程序,它必須在所需的時間內具有有效的使用期限。由線程。要麼確保通過將動態分配的所有權傳遞給線程,讓它做刪除,或者傳遞一個已知的保持確定狀態的指針,以保證其在thread-proc中的使用期限。看起來this滿足後者,所以你應該很好去。

+0

Dammit範圍每次都讓我。有關如何解決的任何建議? – Ben

+0

乾杯,我有我自己的幾個,但他們可能吠叫錯了樹...只有我發現後,我已經離開了森林:) – Ben

+0

而且我們有擡頭。非常感謝。這比我可恥的小堆垃圾代碼heheh要好上百萬倍。 – Ben