2013-05-12 95 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而不是其地址。