0

我正在开发一个多线程服务器应用程序。我有这个结构,我尝试将其传递给 2 个线程:

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";
}

现在我遇到的问题是 mailQueue 线程中指向 SafeQueue 的指针具有 params 结构的地址...参见输出:

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

1 回答 1

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

这应该只是p

您将 a 传递params**mailQueue线程,然后将其转换为params*并取消引用它,这是未定义的行为。在实践中发生的是(because )p->mq的地址,它是构造函数中的值,正如您在输出中看到的那样。*poffsetof(params, mq) == 0pServercout

要修复它,您应该将 a 传递params*给新线程,即变量p而不是它的地址。

于 2013-05-12T23:27:42.393 回答