Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pointer Value is changed when passed through Threadcreate

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.

like image 371
Euler Avatar asked Mar 21 '26 19:03

Euler


2 Answers

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.

like image 80
hmjd Avatar answered Mar 23 '26 07:03

hmjd


You might get a race condition. You delete your class instance right after CreateThread. At this point threadentry() might not start executing yet.

like image 30
Alex Skalozub Avatar answered Mar 23 '26 09:03

Alex Skalozub



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!