Background:
I have two GUI threads: Main and SendEmail in an MFC/Win32 application.
Normally, the main thread spawns the send email thread and continues to run. The send email thread tells the main thread's window to stay disabled and captures the mouse, and when it exits, it enables the main thread's window and releases the mouse.
This gives the user the work-flow of the main application is disabled while they're sending an email. The need to do this in a separate thread has to do with problems with MAPI and Outlook since 2010, where it would lock up the app if it was executed on the main thread.
However, if it so happens that the main application does exit while the send mail thread is still running, the process crashes (the send mail thread tries to enable the main thread's window which no longer exists...)
Goal:
To have the main thread wait for the send mail thread to terminate before terminating
Sticking point:
Currently, the email thread self-destructs (there is no memory management, since it calls delete on itself when its run method finishes). But I want the main thread to keep a reference to this thread so that it can wait on a live one at exit.
I cannot use a weak reference, I don't think, because the main thread really should wait on this thread object (threads are inherently waitable), so I don't want the object that represents this thread to self-destruct while the min thread holds it.
I can use a shared pointer - so that both the application and the running thread effectively keep the thread object alive... but then how to delete the application's copy of the thread object when the thread is finished? (I don't want the thread object to keep on existing for no purpose).
I could post a message from the email thread to the main app thread saying "I'm dying" so that the main thread immediately waits for the thread to terminate and then deletes its reference...
Any better ideas?