2013-05-12 94 views
0

我正在開發一個多線程服務器應用程序。 我有這樣的結構,我試圖傳遞給兩個線程:線程的內存問題

struct params{ 
    SafeQueue<int> *mq; 
    Database *db; 
}; 
class Server{ 
    Server(Database *db){ 
    DWORD sthread, ethread; 
    params *p; 
    p = new params; 
    p->db = db; 
    SafeQueue<int> *msgq = new SafeQueue<int>; 
    p->mq = msgq; 
    cout << "Address of params: " << p << endl; 
    cout << "Address of SafeQueue: " << msgq << endl; 
    cout << "Starting Server...\n"; 
    CreateThread(NULL, 0, smtpReceiver, &p, 0, &sthread); 
    CreateThread(NULL, 0, mQueue, &p, 0, &ethread); 
    } 
} 
DWORD WINAPI mailQueue(LPVOID lpParam){ 
    params *p = (params *) lpParam; 
    SafeQueue<int> *msgQ = p->mq; 
    cout << "Address of params: " << p << endl; 
    cout << "Address of SafeQueue: " << msgQ << endl; 
    cout << "Queue thread started...\n"; 
} 

現在我遇到的問題是指針SafeQueue在mailQueue線程具有PARAMS結構的地址...查看輸出:

Address of params: 0x23878 
Address of SafeQueue: 0x212c8 
Starting Server... 
Address of params: 0x28fe60 
Address of SafeQueue: 0x23878 
Queue thread started... 

回答

2
CreateThread(NULL, 0, mQueue, &p, 0, &ethread); 
           ^^ 

這應該只是p

你傳遞一個params**mailQueue線程,然後將其轉換爲params*並將其解引用,這是未定義的行爲。在實踐中發生的是p->mq*p(因爲​​)的地址,它是Server構造函數中p的值,如您在cout輸出中看到的那樣。

要修復它,您應該將params*傳遞給新線程,即變量p而不是其地址。