excray
excray

Reputation: 2858

C++ Multithreading - When does a child thread exit?

I create a thread to whom a void* to a structure is passed as argument. This structure is created in a class. When this class destructor is called, that is at the end of main, the structure is deleted. So later i see the child thread is launched again, and referring to its void* argument throws an exception as its already deallocated. I was hoping that the child threads gets exited before the destructors are called but that's not happening.

From Exitthread page in MSDN,

However, in C++ code, the thread is exited before any destructors can be called or any other automatic cleanup can be performed.

whats the destructors the above line is referring to?

The child thread executes on a procedure that has a lifetime of the main thread. Using a global flag, i thought i could control the child thread execution. I set the global flag on the last routine that main thread executes. But does global objects get deallocated before the termination of child thread. In that case, even that wont help me.

To summarise, whats the best way i could exit a child thread which has the lifetime of the main thread? I do not want to use terminatethread api.

Edit: Some code sample

//In a method at end of main

void EndofMain()
{
 WaitForSingleObject(globalObj->hMutex, INFINITE)
 globalObj->threadActive = false;
 ReleaseMutex(globalObj->hMutex);
}

void ChildThreadProc(void* data)
{
 while(globalObj->threadActive)
 {
    WaitForSingleObject(globalObj->hMutex, INFINITE)
   //do other stuff
   ReleaseMutex(globalObj->hMutex);
   sleep(1000);
 }
}

Now is there a chance where globalObj is deallocated and then the child thread is called?

Upvotes: 1

Views: 1821

Answers (1)

templatetypedef
templatetypedef

Reputation: 373482

One option would be to have the main thread signal the child thread that it should exit (perhaps by setting a Boolean flag), then using WaitForSingleObject at the end of main() to wait for the thread to terminate before returning and calling the destructors. This prevents the error you've described by forcing the thread to exit (in a safe manner) before destructors fire.

Upvotes: 1

Related Questions