Reputation: 13
I'm working on a multi-threaded server application. I have this struct that I try to pass to 2 Threads:
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, ðread);
}
}
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";
}
Now the issue I'm having is the pointer to SafeQueue in the mailQueue thread has the address of the params struct... See output:
Address of params: 0x23878
Address of SafeQueue: 0x212c8
Starting Server...
Address of params: 0x28fe60
Address of SafeQueue: 0x23878
Queue thread started...
Upvotes: 0
Views: 59
Reputation: 171263
CreateThread(NULL, 0, mQueue, &p, 0, ðread);
^^
This should be just p
You pass a params**
to the mailQueue
thread then cast it to params*
and dereference it, that's undefined behaviour. What happens in practice is that p->mq
is the address at *p
(because offsetof(params, mq) == 0
) which is the value of p
in the Server
constructor, as you're seeing in the cout
output.
To fix it, you should be passing a params*
to the new thread, i.e. the variable p
not its address.
Upvotes: 2