Here is my context. MyApp exits normally by clicking on either the OK or the Cancel dialog button. MyApp also maintains a TCP connection to another app, HerApp. Before MyApp can normally exit by clicking on one of these buttons, it needs to inform HerApp that it is going offline. This advisory message is sent to HerApp via a socket defined using this derived class: class TxSocket : public CAsyncSocket. HerApps TCP listener replies which comes in on MyAppss TxSocket::OnReceive.
My problem is MyApp ends before the TCP OnReceive occurs.
I have thought of several approaches. Obviously, I cannot block the Main thread while the socket interaction completes because it too is running on the Main thread. I can’t let the Main thread go out of scope either because normal app exit in C++ means all its resources are cleaned up including resources used in any other threads (see cppreference Main function: “… destroys the objects with automatic storage duration…” ), so just launching another thread, which has automatic storage, merely to send the advisory message and wait for a receipt, is out of the question too. Statics are destroyed too so no help there. As a result, these techniques can’t be used either: use of std::thread in conjunction with std::packaged_task, the use of std::async or the setting and retrieving of std::promises and std::futures because the get_future object’s get() would block the Main thread too. I could create an intermediary thread that creates these flag objects, but again, they would all get prematurely destroyed on MyApps exit. The [What happens to a detached thread when main() exits?] (What happens to a detached thread when main() exits?) posting explores what happens when you detach a thread, but I found the answers to be non-definitive, at least for me as an app developer.
I need help finding a good and simple C++ approach to solving this synchronization problem which, I predict, will be quite common once we get past the Web HTML era.
Edit 1: In order to clarify the context of my problem, here my MFC on cancel handler:
void MyAppDlg::OnCancel()
{
myApp->UseTcpioEngineToSendHerAppAdvisoryMsgThatMyAppHasCanceledExpectConfirmationReply(); // fails because connection and io objects get destroyed before completion
CDialog::OnCancel();
} // all automatic static etc storage is destroyed and exit is called