I am creating a new thread in which I am passing passing an object of class class demo is defined in .h file
int threadentry(void* data)
{
demo* inst=(demo*) data;
cout << "Value of inst "<<hex << &inst<< endl;//value is different from below
}
int main()
{
while(1)
{
demo* inst=new demo();
cout << "Value of inst "<<hex << &inst<< endl; //value is coming different from above
HANDLE threads;
DWORD threadId1;
if ((threads = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)threadentry,
(void *)inst, 0, &threadId1)) == NULL)
return -1;
delete inst;
system("pause");
}
}
I think value should be different because address is copied in data variable of threadentry. How can I check that these are the same object passed.
The code is printing the address of a pointer, not the address of the object. There are two pointer variables involved (one is declared in main() and the other is the argument of the thread function) so the output is different. Drop the &, address of operator, from the output statements:
cout << "Value of inst "<<hex << inst << endl;
Give ownership of the supplied object to the thread as it knows when it has finished using it. In the posted code the object is deleted after the thread is created, possibly resulting in the thread using a dangling pointer. Move the delete of object from main into the thread.
The signature of the thread function is:
DWORD WINAPI ThreadProc(
_In_ LPVOID lpParameter
);
and it must return a value, the posted code does not.
The code also has a resource leak as the handle returned from CreateThread() is not being closed. Either CloseHandle() immediately if the thread does not need to be joined with or store the thread handles, in a std::vector for example, to be joined with (using WaitForSingleObject for example) and closed later.
You might get a race condition. You delete your class instance right after CreateThread. At this point threadentry() might not start executing yet.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With