1

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?

Mordachai
  • 9,412
  • 6
  • 60
  • 112
  • 1
    can you have the main thread wait for a CEvent that the email thread signals on shutdown? http://stackoverflow.com/questions/14576794/c-windows-mfc-concurrency-get-thread-to-wait-until-particular-state-achieved – Graham Griffiths Mar 13 '14 at 16:22
  • 1
    or this : http://stackoverflow.com/questions/3180164/correct-way-of-checking-if-threads-are-done – Graham Griffiths Mar 13 '14 at 16:29
  • Thanks for the ideas. I went with having the app as the owner of the thread objects, and having the threads post a message to the main thread when they're done. That gives the main thread the ability to delete the object (which is neither here nor there as far as the thread is concerned, so no race conditions). – Mordachai Mar 13 '14 at 17:20

0 Answers0